在Django登录表单中从电子邮件中删除区分大小写 [英] Removing case sensitivity from Email in Django login form
问题描述
在有人将其标记为重复之前,我已经搜索了所有地方,但没有找到。我创建了一个自定义的UserModel,并使用Email作为主要的身份验证ID而不是用户名。
该问题区分大小写,因为它涉及test@gmail.com, Test@gmail.com作为2个不同的帐户。
我需要强迫它作为1个帐户处理,而忽略大小写。
这是我的文件:
models.py
class UserModelManager(BaseUserManager):
def create_user(self,email,password,pseudo):
user = self.model()
user.name = name
user.email = self.normalize_email(email = email)
user.set_password(password)
user.save()
return user
def create_superuser(self,email,password):
'''
用于:python manage.py createsuperuser
'''
user = self.model()
user.name ='admin-yeah'
user.email = self.normalize_email(email = email)
user.set_password(password)
user.is_staff =真
user.is_superuser =真
user.save()
返回用户
类UserModel(AbstractBaseUser,PermissionsMixin):
##人员字段。
email = models.EmailField(max_length = 254,unique = True)
name = models.CharField(max_length = 16)
## [...]
## Django管理字段。
date_joined = models.DateTimeField(auto_now_add = True)
is_active = models.BooleanField(default = True)
is_staff = models.BooleanField(default = False)
USERNAME_FIELD ='电子邮件'
REQUIRED_FIELD = ['电子邮件','名称']
对象= UserModelManager()
def __str __(self):
return self.email
def get_short_name(self):
return self.name [:2] .upper()
def get_full_name(self):
return self.name
views.py
def signup(request):
if request.method =='POST':
signup_form = SignUpForm (request.POST)
如果signup_form.is_valid():
signup_form.save()
用户名= signup_form.cleaned_data.get('用户名')
raw_password = signup_form.cleaned_data .get('password1')
user = authenticate(username = use rname,password = raw_password)
return redirect('signup_confirm')
其他:
signup_form = SignUpForm()
context = {
'signup_form' :signup_form,
}
return render(request,'fostania_web_app / signup.html',context)
def signup_confirm(request):
返回render(request,'fostania_web_app / signup_confirm.html')
表单中的注册表单.py :
class SignUpForm(UserCreationForm):
email = form.CharField(required = True ,help_text ='البريدالإلكترونىالخاصبك-يجبانيكونحقيقى(يستخدملتسجيلالدخول)')
name = form.CharField(required = True,help_text ='إسسسل- = form.CharField(widget = forms.PasswordInput,
help_text ='كلمةالمرور-حاولانتكونسهلةالتذكربالنسبةلك')
password2 = form.CharField(widget = forms.PasswordI nput,
help_text ='تأكيدكلمةالمرور-' ,'name','password1','password2',)
标签= {
'name':'إسمكالحقيقى-سيظهركأسمالبائع',
'email':'البربدالإلكترونى电子邮件',
'password1':'كلمةالمرور',
'password2':'تأكيدكلمةالمرور'
}
我现在需要做的只是使其完全忽略大小写。
更新
这是我的登录文件
urls.py
路径( login /,auth_views .login,name ='login'),
registartion / login.html
< form method = post>
{%csrf_token%}
电子邮件& nbsp;< Br> {{form.username}}
< br>< br>
كلمةالمرور& nbsp;< Br> {{form.password}}
< Br>
< div align = center>
< button class = btn btn-primary Submit>تسجيلالدخول< / button>< br>
< a href = {%url‘signup’%}>< button type = button class = btn btn-warning>
إنشاءحسابجديد< / button>< / a>
< / div>
< / form>
您无需进行太多更改即可完成此任务-在您的情况下,您只需要更改表单并使用Django内置的表单数据清理器,或通过创建自定义字段。
您应该使用 EmailField
而不是 CharField
用于内置验证。另外,您没有发布AuthenticationForm,但我想您已将其更改为包括电子邮件
而不是用户名
。
使用数据清理器:
class SignUpForm(UserCreationForm):
#您的代码
email = form.EmailField(required = True)
def clean_email(self):
data = self.cleaned_data ['email']
返回data.lower ()
类AuthenticationForm(forms.Form):
#您的代码
email = form.EmailField(required = True)
def clean_email(self):
data = self.cleaned_data ['email']
返回data.lower()
具有自定义字段:
class EmailLowerField(forms.EmailField):
def to_python(self,value) :
返回值.lower()
类SignUpForm(UserCreationForm):
#您的代码
email = EmailLowerField(required = True)
类认证表单(forms.Form):
#您的代码
email = EmailLowerField(required = True)
通过这种方式,您可以确保将每封电子邮件都以小写形式保存到数据库中,并且对于每次登录尝试,在与数据库值进行比较之前,均将小写形式的电子邮件进行翻译。
Before anyone marks it as duplicate, I've searched everywhere and didn't find. I've created a custom UserModel and used Email as main authenticating id instead of username.
The problem that it is case sensitive, as it counts test@gmail.com,Test@gmail.com as 2 different accounts.
I need to force it to deal with both as 1 account ignoring if it upper or lower case.
here are my files :
models.py
class UserModelManager(BaseUserManager):
def create_user(self, email, password, pseudo):
user = self.model()
user.name = name
user.email = self.normalize_email(email=email)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password):
'''
Used for: python manage.py createsuperuser
'''
user = self.model()
user.name = 'admin-yeah'
user.email = self.normalize_email(email=email)
user.set_password(password)
user.is_staff = True
user.is_superuser = True
user.save()
return user
class UserModel(AbstractBaseUser, PermissionsMixin):
## Personnal fields.
email = models.EmailField(max_length=254, unique=True)
name = models.CharField(max_length=16)
## [...]
## Django manage fields.
date_joined = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELD = ['email', 'name']
objects = UserModelManager()
def __str__(self):
return self.email
def get_short_name(self):
return self.name[:2].upper()
def get_full_name(self):
return self.name
signup view in views.py
def signup(request):
if request.method == 'POST':
signup_form = SignUpForm(request.POST)
if signup_form.is_valid():
signup_form.save()
username = signup_form.cleaned_data.get('username')
raw_password = signup_form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
return redirect('signup_confirm')
else:
signup_form = SignUpForm()
context = {
'signup_form': signup_form,
}
return render(request, 'fostania_web_app/signup.html', context)
def signup_confirm(request):
return render(request, 'fostania_web_app/signup_confirm.html')
the sign up form in forms.py:
class SignUpForm(UserCreationForm):
email = forms.CharField(required=True, help_text='البريد الإلكترونى الخاص بك - يجب ان يكون حقيقى (يستخدم لتسجيل الدخول) ')
name = forms.CharField(required=True, help_text='إسمك الحقيقى - سيظهر كأسم البائع')
password1 = forms.CharField(widget=forms.PasswordInput,
help_text='كلمة المرور - حاول ان تكون سهلة التذكر بالنسبة لك')
password2 = forms.CharField(widget=forms.PasswordInput,
help_text='تأكيد كلمة المرور - إكتب نفس كلمة المرور السابقة مرة أخرى')
class Meta:
model = UserModel
fields = ('email','name', 'password1', 'password2', )
labels = {
'name': 'إسمك الحقيقى - سيظهر كأسم البائع',
'email': 'البربد الإلكترونى Email',
'password1': 'كلمة المرور',
'password2': 'تأكيد كلمة المرور'
}
All that I need now is to make it simply ignores the case sensitivity.
update
here is my login files
urls.py
path('login/', auth_views.login, name='login'),
registartion/login.html
<form method="post">
{% csrf_token %}
البريد الإلكترونى E-Mail <Br>{{ form.username }}
<br><br>
كلمة المرور <Br>{{ form.password }}
<Br><br>
<div align="center">
<button class ="btn btn-primary" submit>تسجيل الدخول</button><br><br>
<a href="{% url 'signup' %}"><button type="button" class="btn btn-warning">
إنشاء حساب جديد</button></a>
</div>
</form>
You don't need to change much to accomplish this - in your case you just need to change the form and make use of Django's built-in form data cleaners or by making a custom field.
You should use the EmailField
instead of a CharField
for built-in validation. Also you did not post your AuthenticationForm, but i presume you have changed it to include email
instead of username
.
With data cleaners:
class SignUpForm(UserCreationForm):
# your code
email = forms.EmailField(required=True)
def clean_email(self):
data = self.cleaned_data['email']
return data.lower()
class AuthenticationForm(forms.Form):
# your code
email = forms.EmailField(required=True)
def clean_email(self):
data = self.cleaned_data['email']
return data.lower()
With a custom field:
class EmailLowerField(forms.EmailField):
def to_python(self, value):
return value.lower()
class SignUpForm(UserCreationForm):
# your code
email = EmailLowerField(required=True)
class AuthenticationForm(forms.Form):
# your code
email = EmailLowerField(required=True)
This way you can make sure that each email is saved to your database in lowercase and that for each login attempt the email is lowercased before compared to a database value.
这篇关于在Django登录表单中从电子邮件中删除区分大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!