首页 文章

用户通过电子邮件验证和django中数据库的密码

提问于
浏览
1

我是django的初学者 . 我正在开展一个项目,其中客户和公司拥有自己的帐户models.py是:

class Company_SignUp(models.Model):
   comp_name = models.CharField(_('Company Name'), max_length=30)
   email = models.EmailField(_('E-mail'), unique=True)
   raise forms.ValidationError("This email address already exists.")
   password1 = models.CharField(_('Password'), max_length=128)
   password2 = models.CharField(_('Confirm Password'), max_length=30)

   def __unicode__(self):
       return smart_unicode(self.comp_name)

class Customer_SignUp(models.Model):
   cust_name = models.CharField(_('Customer Name'), max_length=30)
   email = models.EmailField(_('E-mail'), unique=True)
   password1 = models.CharField(_('Password'), max_length=128)
   password2 = models.CharField(_('Confirm Password'), max_length=30) 

   def __unicode__(self):
       return smart_unicode(self.cust_name)

我的forms.py是:

class Company(forms.ModelForm):
    class Meta:
        model = Company_SignUp
        widgets = {
          'password1': forms.PasswordInput(),
          'password2': forms.PasswordInput(),
        }
        fields = ('email','password1','password2','comp_name')

    def clean(self):
        if 'password1' in self.cleaned_data and 'password2' in       self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError(_("The two password fields did not match."))
            elif len(self.cleaned_data['password1']) < 8:
                raise forms.ValidationError(_("The password must be 8 characters long."))

        return self.cleaned_data

class Customer(forms.ModelForm):
    class Meta:
        model = Customer_SignUp
        widgets = {
            'password1': forms.PasswordInput(),
            'password2': forms.PasswordInput(),
        }  
    def clean(self):
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError(_("The two password fields did not match."))
            elif len(self.cleaned_data['password1']) < 8:
              raise forms.ValidationError(_("The password must be 8 characters long."))

        return self.cleaned_data

我将如何使用他们的电子邮件和密码验证公司或客户 . 我试过authenticate()但它不起作用 . 如何在注册期间检查,给出的电子邮件地址已经存在

好吧,现在我创建了一个后端,它是:来自django.contrib.auth.models从prmanager.models导入用户导入Company_SignUp,Customer_SignUp

class EmailBackend(object):
    def authenticate(self, username=None, password=None):
        try:
            o = Company_SignUp.objects.get(email=username, password1=password)
        except Company_SignUp.DoesNotExist:
            try:
                o = Customer_SignUp.objects.get(email=username, password1=password)
            except Customer_SignUp.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

但现在我无法使用超级用户凭据登录管理页面 . 我该怎么办

1 回答

  • 1

    Models

    考虑从 django.contrib.auth.models 扩展 User 模型 . 如果您不想这样做,请跳到下一部分(身份验证) .

    from django.contrib.auth.models import User
    
    class Customer(User):
        # extra fields
    

    User 模型具有常见字段,例如 usernamefirst_namelast_nameemail 等 . 您只需指定模型可能具有的任何额外属性 .

    Django文档建议扩展 AbstractBaseUser ,这也可能适合你 .

    在这里阅读更多:https://docs.djangoproject.com/en/1.7/topics/auth/customizing/#extending-the-existing-user-model

    Authentication

    对于基于电子邮件的身份验证,您需要编写自己的身份验证后端:https://docs.djangoproject.com/en/1.7/topics/auth/customizing/#writing-an-authentication-backend

    准备好后,您需要接受电子邮件/密码并使用 authenticatelogin 进行身份验证 .

    from django.contrib.auth import authenticate, login
    
    def my_view(request):
        email = request.POST['email']
        password = request.POST['password']
        user = authenticate(email=email, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                # Redirect to a success page.
            else:
                # Return a 'disabled account' error message
        else:
            # Return an 'invalid login' error message.
    

    上面的代码段来自文档,我修改了它以适合您的用例 .

    有关Django中身份验证的更多信息:https://docs.djangoproject.com/en/1.7/topics/auth/default/#how-to-log-a-user-in

相关问题