Reputation: 2907
That's how I"ve extended User model:
class User(AbstractBaseUser):
email = models.EmailField(verbose_name='email',max_length=255,unique=True, db_index=True,)
username = models.CharField(verbose_name='username', max_length=255, unique=True)
first_name = models.CharField(verbose_name='first_name', max_length=255, blank=True)
last_name = models.CharField(verbose_name='last_name', max_length=255, blank=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = UserManager()
avatar = models.ImageField(upload_to='profile_images', blank=True)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['username']
def get_full_name(self):
return '%s %s' % (self.first_name, self.last_name,)
def get_short_name(self):
return self.username
def __unicode__(self):
return self.email
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
@property
def is_staff(self):
return self.is_admin
It works good , but after new user registration I can't log in with his username and password and in my database I have now 2 tables with users
auth_user - old users
blog_user - new extended users
And I can log in only with users from auth_user.
That's what I have for login in views.py:
@csrf_protect
def loginn(request):
c = {}
c.update(csrf(request))
return render_to_response("login/login.html", c)
@csrf_protect
def auth_view(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return render_to_response('login/loggedin.html',RequestContext(request))
else:
return HttpResponseRedirect('/posts/invalid')
So , how can I log in with user from my new , extended table ?
Upvotes: 1
Views: 97
Reputation: 1483
In order to allow a custom User model to be used within the authenticate()
method, Django requires setting the AUTH_USER_MODEL
setting.
https://docs.djangoproject.com/en/dev/topics/auth/customizing/#substituting-a-custom-user-model
For your example code it would be AUTH_USER_MODEL = 'blog.User'
within settings.py
The authenticate()
method makes a call to get_user_model()
which goes and finds if the AUTH_USER_MODEL setting is set, and then uses that as it's base for the model which to authenticate against.
Please be sure to read the documentation on substituting a custom user model within Django. There are a handful of caveats that you should be aware of before making a decision to switch the auth user model.
If it's possible, I would recommend just extending the base auth user model to include any application specific fields you would need because it appears you are still logging users in via Username. https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model
Upvotes: 1