Django使用自己的模型自定义登录

jay*_*l d 2 django django-models

我正在使用Django1.4和PostgreSQL.我正在开发一个应用程序,其中我有两个模型,即学生,公司.

class students(models.Model):

    first_name = models.CharField(**option)
    last_name = models.CharField(**option)
    username = models.EmailField(max_length=100, unique=True)
    password = models.CharField(_('password'), max_length=128)
    # Some other attributes for Student models



class company(models.Model):
    compnay_name = models.CharField(**option)
    username = models.EmailField(max_length=100, unique=True)
    password = models.CharField(_('password'), max_length=128)
    #Some other attributes for company models
Run Code Online (Sandbox Code Playgroud)

我的要求:

  1. 学生和公司可以创建新的个人资料(提供注册表格)
  2. 为学生/公司创建新的个人资料,用户名即电子邮件ID应该是唯一的.即学生和公司模型中不应存在电子邮件ID.(任务完成)
  3. 为学生和公司登录创建了2个登录表单.

问题:

  1. 由于我没有使用或扩展用户模型,我无法使用django内置登录和身份验证方法.

  2. 如何编写自定义身份验证方法,该方法应检查学生/公司用户名和密码中的用户凭据.(为学生和公司提供2种不同的登录表格)

请帮我.

感谢您阅读我的查询.

backend.py

class LoginBackend:
    def authenticate(self, username=None, password=None, model=None):
        if model == "Student":
            lookup_model = Student
        elif model == "Employer":
            lookup_model = Employer
        try:
            user = lookup_model.objects.get(email=username)
         except Exception, e:
            return None
    return user
Run Code Online (Sandbox Code Playgroud)

views.py

def check_auth(request):
    user_object = Student.objects.get(email__iexact = unicode(email))
    if check_password(password, user_object.password):
        print authenticate(username = email, password = password, model = "Student")
        login(request, user_object)
Run Code Online (Sandbox Code Playgroud)

settings.py

AUTHENTICATION_BACKENDS =("proj.app.backends.LoginBackend",)

错误

/xx/login /的AttributeError

'学生'对象没有属性'后端'

Pau*_*ine 7

编写自定义身份验证后端.读这个:

[更新]

通过编写和注册自定义身份验证后端,您只需使用标准的Django身份验证模式.看看你的示例代码,我的印象是你对它有不同的理解.

由于电子邮件是您的唯一密钥,我建议使用电子邮件登录密钥,首先检查针对学生的登录名/密码,如果失败,请查看公司.

from django.contrib.auth.models import User
class JayapalsBackend(object):
    def authenticate(self, username=None, password=None):
         try:
             o = Student.objects.get(email=username, password=password)
         except Student.DoesNotExist:
             try:
                 o = Company.objects.get(email=username, password=password)
             except Company.DoesNotExist:
                 return None
         return User.objects.get(email=o.email)
    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None
Run Code Online (Sandbox Code Playgroud)

然后只使用标准的Django装饰器:

@login_required
def some_private_view(request):
    ...
Run Code Online (Sandbox Code Playgroud)