我是如何扩展用户模型的:
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
效果很好,但在新用户注册后,我无法使用他的用户名和密码登录 在我的数据库中,我现在有2个用户表
auth_user - 旧用户
blog_user - 新的扩展用户
我只能与来自 auth_user 的用户登录。
这是我在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')
那么,我如何从新的扩展表中用户登录?
答案 0 :(得分:1)
为了允许在authenticate()
方法中使用自定义用户模型,Django需要设置AUTH_USER_MODEL
设置。
https://docs.djangoproject.com/en/dev/topics/auth/customizing/#substituting-a-custom-user-model
对于您的示例代码,它在settings.py
中为AUTH_USER_MODEL = 'blog.User'
authenticate()
方法调用get_user_model()
,然后查找是否设置了AUTH_USER_MODEL设置,然后将其用作要进行身份验证的模型的基础。
请务必阅读有关在Django中替换自定义用户模型的文档。在决定切换auth用户模型之前,您应该注意一些警告。
如果可能,我建议只扩展基本身份验证用户模型,以包含您需要的任何特定于应用程序的字段,因为看起来您仍然通过用户名登录用户。 https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model