Reputation: 605
I have a Django app that needs an extra field (a manytomany mapping to a Book class) and I did that by extending the AbstractUser.
If you’re entirely happy with Django’s User model and you just want to add some additional profile information, you can simply subclass django.contrib.auth.models.AbstractUser and add your custom profile fields. This class provides the full implementation of the default User as an abstract model.
class User(AbstractUser):
entitledBooks = models.ManyToManyField(Book)
I added the model in my settings.py
AUTH_USER_MODEL = 'BookRServer.User'
But how do I create a user (programmatically) ?
user = User.objects.create_user() doesn't work.
Upvotes: 1
Views: 434
Reputation: 140
The create_user manager method only accepts three arguments, username, email (optional), and password (optional).
You can do so:
bookset=Book.objects.all()
user = User.objects.create_user('testuser',email='[email protected]')
user.entitledBooks=bookset
user.save()
Upvotes: 1
Reputation: 4763
At the simple possible, loosely coupled way is to create a One-to-One relationship user profile model containing your many-to-many relationship
class UserProfile(models.Model):
user = model.OneToOneField(User)
# your many-to-many field here
# create user
u = User(username="", password="", email="", ...)
u.save()
u.userprofile(your fields..here)
u.userprofile.save()
This is typically same in all django versions. What basically django 1.6 deprecated is to provide a model method get_profile
and some relevant settings..
Unless you really want to build User
model right from the ground as per requirements, you don't have to really use AUTH_USER_MODEL
..
Detaching User Profile from User model also helps in the long run
Upvotes: 0