我目前正在使用Django创建一个网站,我正在处理日志记录表单。
我在models.py
文件中创建了一个SimpleUser类:
class SimpleUser(AbstractBaseUser):
username = models.TextField(max_length=40)
firstname = models.TextField(max_length=40)
lastname = models.TextField(max_length=40)
email = models.EmailField()
GENDER_LIST = (
(0, 'Homme'),
(1, 'Femme'),
)
gender = models.IntegerField(choices=GENDER_LIST, default=0)
society = models.TextField(max_length=255)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['society', 'username', 'email']
现在,这是我views.py
中的日志表单:
def loginview(request):
if request.POST:
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
if user is not None:
if user.is_active:
auth.login(request, user)
return HttpResponseRedirect('/moncompte/')
else:
errors.append("Disabled account.")
else:
if username == "" or password == "":
errors.append("Fill the two fields!")
else:
errors.append("Bad matching account/username.")
c = {
'headerlinks': hlinks,
'footerlinks': footerlinks, #These are defined earlier
'username': username,
'password': password,
'errors': errors,
}
c.update(csrf(request))
print c
return jinja_render_to_response('loginview.jhtml', c)
哦,我也在使用Jinja,但没有问题:) 问题是,当我尝试使用此表单登录时,Django会将用户名和密码与超级用户匹配,即用于登录管理面板的用户名和密码。当然,我想将登录信息与我的对象SimpleUser相匹配。这显然不起作用。有什么帮助吗?
答案 0 :(得分:1)
您实际需要做的是创建自定义身份验证后端并将其导入settings.py文件中。
from models import SimpleUser
class CustomAuth(object):
def authenticate(self, username=None, password=None):
try:
user = SimpleUser.objects.get(username=username)
if user.check_password(password):
return user
except SimpleUser.DoesNotExist:
return None
def get_user(self, user_id):
try:
user = SimpleUser.objects.get(pk=user_id)
if user.is_active:
return user
return None
except SimpleUser.DoesNotExist:
return None
和settings.py
AUTHENTICATION_BACKENDS = ('apps.accounts.auth.CustomAuth')