0

我目前正在使用 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 匹配。而这显然是行不通的。请问有什么帮助吗?

4

1 回答 1

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')
于 2013-05-31T09:05:57.363 回答