gpt4 book ai didi

python - 如何在 Django 2.0 中为小写用户创建验证器?

转载 作者:行者123 更新时间:2023-11-30 22:06:31 25 4
gpt4 key购买 nike

我的网站已启动并正在运行。然而,愚蠢的我没有放入验证器来检查用户和用户名是否只能是小写(我只意识到DJANGO允许大写的用户和用户名)。虽然我已经提出了警告,但用户通常会忽略在注册表单中仍然写大写字母或至少大写字母。然后我遇到了 slugs 无法工作的问题,此后我必须手动更改他们的用户名。我不想改变蛞蝓的行为,我可以向某人寻求帮助来改变我的观点吗?我也尝试过 .lower() .format() 但没有成功。我对验证器的能力很弱。

表单.py

from django.contrib.auth.models import User
from django import forms
from captcha.fields import CaptchaField

class SignUpForm(forms.ModelForm):

captcha = CaptchaField()
password = forms.CharField(max_length= 15, widget=forms.PasswordInput)

class Meta:
model = User
fields = ['username', 'email', 'password']

View .py

   from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth import authenticate, login
from django.views import generic
from django.views.generic import View
from home.forms import SignUpForm



class SignUpFormView(View):
form_class = SignUpForm
template_name = 'home/signup.html'

#if there is no sign up yet
def get(self,request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})


#if going to sig up
def post(self,request):
form = self.form_class(request.POST)


if form.is_valid():
#it takes information but does save it
user = form.save(commit = False)
#cleaned normalized data
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.set_password(password)
user.save()




#returns if it is all correct

user = authenticate(username = username, password = password)

if user is not None:

if user.is_active:
login(request, user)
return redirect("userprofile:newprofile")

return render(request, self.template_name, {'form': form})

最佳答案

您可以在SignupForm中添加验证:

from django.contrib.auth.models import User
from django import forms
from captcha.fields import CaptchaField

class SignUpForm(forms.ModelForm):

captcha = CaptchaField()
password = forms.CharField(max_length= 15, widget=forms.PasswordInput)

def clean_username(self):
data = self.cleaned_data['username']
if <b>not data.islower()</b>:
raise forms.ValidationError("Usernames should be in lowercase")
return data

class Meta:
model = User
fields = ['username', 'email', 'password']

因此,如果 data.islower() 检查失败(用户名 包含大写字符),它将引发 ValidationError,并且因此该表格无效。

请注意,islower() 仅检查基于大小写的字符,因此如果字符串包含数字,它仍然会成功。因此,您可能需要微调检查。或如 documentation of str.islower 中指定:

Return True if all cased characters in the string are lowercase and there is at least one cased character, False otherwise.

另一种方法可能是将数据转换为小写,这样输入 'FooBar' 的用户就会得到用户名 foobar,尽管这可能会导致以下事实:用户会感到困惑,因为他们选择的用户名不是他们得到的用户名。

关于python - 如何在 Django 2.0 中为小写用户创建验证器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52698322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com