0

我正在使用 Django 1.5。我的用户模型是:

class User(AbstractBaseUser):
    #id = models.IntegerField(primary_key=True)
    #identifier = models.CharField(max_length=40, unique=True, db_index=True)
    username = models.CharField(max_length=90, unique=True, db_index=True)
    create_time = models.DateTimeField(null=True, blank=True)
    update_time = models.DateTimeField(null=True, blank=True)
    email = models.CharField(max_length=225)
    #password = models.CharField(max_length=120)
    external = models.IntegerField(null=True, blank=True)
    deleted = models.IntegerField(null=True, blank=True)
    purged = models.IntegerField(null=True, blank=True)
    form_values_id = models.IntegerField(null=True, blank=True)
    disk_usage = models.DecimalField(null=True, max_digits=16, decimal_places=0, blank=True)
    #last_login = models.DateTimeField()

    objects = UserManager()
    USERNAME_FIELD = 'username'
    class Meta:
        db_table = u'galaxy_user'

我无法使用正确的用户名和密码进行身份验证。我的登录功能是:

def login_backend(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            login(request, user)
            return HttpResponseRedirect('/overview/')
        else:
            return HttpResponseRedirect('/login_backend/')
    else:
        return render_to_response('login_backend.html', context_instance=RequestContext(request))

我究竟做错了什么?

4

2 回答 2

0

首先更新您的用户模型,它没有密码。您的电子邮件字段不是字符字段,我认为它是 EmailField,您的密码也不是字符字段。请搜索正确的字段。密码必须是哈希...

后端.py

from django.conf import settings
from app_name.models import User

class AuthBackend:
    def authenticate(self, username=None, password=None):
        if '@' in username:
            kwargs = {'email': username}
        else:
            kwargs = {'username': username}
        try:
            user = User.objects.get(**kwargs)
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

通过模型创建“check_password”函数。这种检查的方式是,在将输入密码与保存在数据库中的密码进行比较之前,输入密码必须经过哈希处理。

更新设置.py

AUTHENTICATION_BACKENDS = (
    'app_name.backend.AuthBackend',
    'django.contrib.auth.backends.ModelBackend',
)
于 2013-02-14T12:14:33.860 回答
0

您是否在 settings.py 中配置了用户模型?

AUTH_USER_MODEL = 'myapp.User'

如果您已经运行了syncdb,则必须删除数据库并再次运行它。请参阅:https ://docs.djangoproject.com/en/1.5/topics/auth/customizing/#substituting-a-custom-user-model

于 2013-02-12T10:37:39.560 回答