我有一个Django的clean方法的问题,因为表单的clean方法不会加载模板中的错误。有人能帮助我吗?
template.html
{% extends "index.html" %}
{% block header %}
<div id="container-register">
<div class="logo-register">Zarejestruj się</div>
<div class="register-form">
<form method="post">
{% csrf_token %}
{% for field in form %}
{{ field }} {{ field.errors }} <br>
{% endfor %}
<input type="submit" value="Zarejestruj">
</form>
</div>
</div>
{% endblock %}
view.py
class AddUserView(View):
template_name = 'add_user.html'
def get(self,request):
return render(request, self.template_name,{
'form': AddUserForm()
})
def post(self,request):
form = AddUserForm(request.POST)
if form.is_valid():
User.objects.create_user(
username=form.cleaned_data.get('username'),
email=form.cleaned_data.get('email'),
password=form.cleaned_data.get('password'),
first_name=form.cleaned_data.get('first_name'),
last_name=form.cleaned_data.get('last_name')
)
return redirect('/login')
else:
return render(request, self.template_name, context={
'form': AddUserForm()
})
forms.py
class AddUserForm(forms.Form):
username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Nazwa użytkownika'}), max_length=100)
password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Hasło'}), max_length=100)
password_repeat = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Powtórz hasło'}),
max_length=100)
first_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Imię'}), max_length=100)
last_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Nazwisko'}), max_length=100)
email = forms.EmailField(widget=forms.TextInput(attrs={'placeholder': 'Email'}), max_length=100)
def clean_username(self):
if User.objects.filter(username=self.cleaned_data.get('username')).exists():
raise ValidationError('Ten login jest już zajęty')
return self.cleaned_data.get('username')
def clean_password_repeat(self):
if self.cleaned_data.get('password') != self.cleaned_data.get('password_repeat'):
raise ValidationError('Podane hasła różnią się od siebie!')
return self.cleaned_data.get('password_repeat')
我检查了页面源代码,看看errors类是否添加到了html文件中。
1条答案
按热度按时间cetgtptt1#
在post方法中,在模板上下文中创建一个新表单,而不是重用现有的包含数据和错误的表单: