gpt4 book ai didi

django - 如何解决 'ValidationError' 对象没有属性 'strip' 问题?

转载 作者:行者123 更新时间:2023-12-04 08:38:38 25 4
gpt4 key购买 nike

我想添加或提出验证注册表,但出现此错误: 'ValidationError' 对象没有属性 'strip' 我怎么能跳过它?
如果您能在解决此问题后告诉我验证注册表单的正确方法,请告诉我这些问题,我将不胜感激。先感谢您

class SignUp(UserCreationForm):
def __init__(self, *args, **kwargs):
super(SignUp, self).__init__(*args, **kwargs)

self.error_messages = {
'username_match': 'username is already exist',
'email_match': 'Email is already exist',
'password_mismatch': 'these two password isn\'t match try again'
}
email = forms.EmailField(required=True)
first_name = forms.CharField(required=True)
last_name = forms.CharField(required=True)
# password1 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'}))
# password2 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password'}))

class Meta:
model = User
fields = ['username',
'first_name',
'last_name',
'password1',
'password2',
'email']

def clean_email(self):
email = self.cleaned_data.get('email')
if User.objects.filter(email=email).exists():
return forms.ValidationError(
self.error_messages['email_match'],
)
return email

def clean_username(self):
username = self.cleaned_data.get('username')
if User.objects.filter(username=username).exists():
return forms.ValidationError(
self.error_messages['username_match'],
)
return username

def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
return forms.ValidationError(
self.error_messages['password_mismatch'],
)
return password2

def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
View .py
def register(request):
form = SignUp(None)
if request.method == 'POST':
form = SignUp(request.POST)
if form.is_valid():
form.save()
return redirect('accounts:login')
return form.errors
return render(request, 'accounts/register.html', {'form': form})
编辑新问题:
Traceback (most recent call last):
File "/media/medo/BE4C6BE74C6B98C3/Cources/Django/all git/Django projects/Es2al/Es2al2/website/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/media/medo/BE4C6BE74C6B98C3/Cources/Django/all git/Django projects/Es2al/Es2al2/website/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/media/medo/BE4C6BE74C6B98C3/Cources/Django/all git/Django projects/Es2al/Es2al3/website/accounts/views.py", line 73, in register
return render(request, 'accounts/register.html', {'form': form})
File "/media/medo/BE4C6BE74C6B98C3/Cources/Django/all git/Django projects/Es2al/Es2al2/website/venv/lib/python3.8/site-packages/django/shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "/media/medo/BE4C6BE74C6B98C3/Cources/Django/all git/Django projects/Es2al/Es2al2/website/venv/lib/python3.8/site-packages/django/template/loader.py", line 62, in render_to_string
return template.render(context, request)
File "/media/medo/BE4C6BE74C6B98C3/Cources/Django/all git/Django projects/Es2al/Es2al2/website/venv/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render
return self.template.render(context)
File "/media/medo/BE4C6BE74C6B98C3/Cources/Django/all git/Django projects/Es2al/Es2al2/website/venv/lib/python3.8/site-packages/django/template/base.py", line 168, in render
with context.bind_template(self):
File "/usr/lib/python3.8/contextlib.py", line 113, in __enter__
return next(self.gen)
File "/media/medo/BE4C6BE74C6B98C3/Cources/Django/all git/Django projects/Es2al/Es2al2/website/venv/lib/python3.8/site-packages/django/template/context.py", line 244, in bind_template
updates.update(processor(self.request))

Exception Type: ValueError at /accounts/register/
Exception Value: dictionary update sequence element #0 has length 207; 2 is required
网址.py
urlpatterns = [
path('register/', views.register, name='register'),
]

最佳答案

你不应该返回 ValidationError ,但是 raise它。来自 return这样做,表单假定 username 的结果等是ValidationError s:

def clean_email(self):
email = self.cleaned_data.get('email')
if User.objects.filter(email=email).exists():
raise forms.ValidationError( # ← raise instead of return
self.error_messages['email_match'],
)
return email
这个原则应该适用于所有 clean_…方法。
在您看来,您还可以不返回 form.errors ,或者至少不是直接的,你可以 print form.errors ,并将它们传递给上下文,但 View 应返回 HttpResponse目的:
def register(request):
form = SignUp()
if request.method == 'POST':
form = SignUp(request.POST)
if form.is_valid():
form.save()
return redirect('accounts:login')
# return form.errors
return render(request, 'accounts/register.html', {'form': form})

关于django - 如何解决 'ValidationError' 对象没有属性 'strip' 问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64671476/

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