通过 django 数据库中的电子邮件和密码进行用户身份验证
user authentication by email and password from database in django
我是 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
但是现在我无法使用超级用户凭据登录管理页面。我该怎么办
型号
考虑像这样从 django.contrib.auth.models
扩展 User
模型。如果您不想这样做,请跳到下一节(身份验证)。
from django.contrib.auth.models import User
class Customer(User):
# extra fields
User
模型有username
、first_name
、last_name
、email
等常用字段,你只需要指定任何额外的您的模型可能具有的属性。
Django 文档建议扩展 AbstractBaseUser
,这可能也适合您。
在此处阅读更多内容:https://docs.djangoproject.com/en/1.7/topics/auth/customizing/#extending-the-existing-user-model
身份验证
对于基于电子邮件的身份验证,您需要编写自己的身份验证后端:https://docs.djangoproject.com/en/1.7/topics/auth/customizing/#writing-an-authentication-backend
设置好后,您需要接受电子邮件/密码并使用 authenticate
和 login
进行身份验证。
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
我是 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
但是现在我无法使用超级用户凭据登录管理页面。我该怎么办
型号
考虑像这样从 django.contrib.auth.models
扩展 User
模型。如果您不想这样做,请跳到下一节(身份验证)。
from django.contrib.auth.models import User
class Customer(User):
# extra fields
User
模型有username
、first_name
、last_name
、email
等常用字段,你只需要指定任何额外的您的模型可能具有的属性。
Django 文档建议扩展 AbstractBaseUser
,这可能也适合您。
在此处阅读更多内容:https://docs.djangoproject.com/en/1.7/topics/auth/customizing/#extending-the-existing-user-model
身份验证
对于基于电子邮件的身份验证,您需要编写自己的身份验证后端:https://docs.djangoproject.com/en/1.7/topics/auth/customizing/#writing-an-authentication-backend
设置好后,您需要接受电子邮件/密码并使用 authenticate
和 login
进行身份验证。
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