會有人知道爲什麼下面的表格是不是驗證:Django註冊視圖無法驗證表單?
forms.py:
class UserRegistrationForm(UserCreationForm):
required_css_class = 'required'
username = forms.CharField(label='Username')
email = forms.EmailField(label='Email')
password = forms.CharField(label='Password')
password2 = forms.CharField(label='Password2')
class Meta:
model = User
fields = ('first_name', 'last_name', 'username', 'email')
def __init__(self, *args, **kwargs):
super(UserRegistrationForm, self).__init__(*args, **kwargs)
self.fields['username'].widget = TextInput(attrs={'placeholder': 'Username'})
self.fields['username'].required = True
self.fields['username'].error_messages = {'required': 'Please enter your username'}
self.fields['email'].widget = EmailInput(attrs={'placeholder': 'Email'})
self.fields['email'].required = True
self.fields['email'].error_messages = {'required': 'Please enter your email'}
self.fields['first_name'].widget = TextInput(attrs={'placeholder': 'Forename'})
self.fields['first_name'].required = True
self.fields['first_name'].error_messages = {'required': 'Please enter your first name'}
self.fields['last_name'].widget = TextInput(attrs={'placeholder': 'Surname'})
self.fields['last_name'].required = True
self.fields['last_name'].error_messages = {'required': 'Please enter your last name'}
self.fields['password'].widget = PasswordInput(attrs={'placeholder': 'Password'})
self.fields['password'].required = True
self.fields['password'].error_messages = {'required': 'Please enter your Password'}
self.fields['password2'].widget = PasswordInput(attrs={'placeholder': 'Confirm password'})
self.fields['password2'].required = True
self.fields['password2'].error_messages = {'required': 'Please confirm your Password'}
def cleaned_username(self):
username = self.cleaned_data.get('username')
username_qs = User.objects.filter(username=username)
if username_qs.exists():
raise forms.ValidationError("I'm sorry, that username already exists.")
def cleaned_email(self):
email = self.cleaned_data.get('email')
email_qs = User.objects.filter(email=email)
if email_qs.exists():
raise forms.ValidationError("I'm sorry, this email has already been taken.")
def cleaned_password2(self):
password = self.cleaned_data.get('password')
password2 = self.cleaned_data.get('password2')
if password != password2:
raise forms.ValidationError("Your passwords do not match.")
templates.html:
<form class="contact-form" name="contact-form" method="POST" action="." enctype='multipart/form-data'>
<div class="form-group">
{% csrf_token %}
<input class="form-control" type="text" name="{{ form.first_name.name }}" {% if form.first_name.value %}value="{{ form.first_name.value }}"{% endif %} placeholder="Forename"/>
{% if form.firstname.errors %}<span class="form-error error-above">{{ form.first_name.errors.as_text }}</span>{% endif %}
<input class="form-control" type="text" name="{{ form.last_name.name }}" {% if form.last_name.value %}value="{{ form.last_name.value }}"{% endif %} placeholder="Surname"/>
{% if form.lastname.errors %}<span class="form-error error-above">{{ form.last_name.errors.as_text }}</span>{% endif %}
<input class="form-control" type="text" name="{{ form.username.name }}" {% if form.username.value %}value="{{ form.username.value }}"{% endif %} placeholder="Username"/>
{% if form.username.errors %}<span class="form-error error-above">{{ form.username.errors.as_text }}</span>{% endif %}
<input class="form-control" type="text" name="{{ form.email.name }}" {% if form.email.value %}value="{{ form.email.value }}"{% endif %} placeholder="Email"/>
{% if form.email.errors %}<span class="form-error error-above">{{ form.email.errors.as_text }}</span>{% endif %}
<input class="form-control" type="password" name="{{ form.password.name }}" {% if form.password.value %}value="{{ form.password.value }}"{% endif %} placeholder="Password"/>
{% if form.password.errors %}<span class="form-error error-above">{{ form.password.errors.as_text }}</span>{% endif %}
<input class="form-control" type="password" name="{{ form.password2.name }}" {% if form.password2.value %}value="{{ form.password2.value }}"{% endif %} placeholder="Confirm Password"/>
{% if form.password2.errors %}<span class="form-error error-above">{{ form.password2.errors.as_text }}</span>{% endif %}
<button type="submit" class="btn btn-primary" value='{{ title }}'>Sign Up</button>
</form>
形式只是沒有驗證 - 我想這可能與templates.html有關,但很難確切地知道沒有錯誤被拋出。根據我所定義的控制流程,我確信我輸入的細節都是正確的。
views.py:
def register(request):
title = "Register"
if request.method == 'POST':
form = UserRegistrationForm(request.POST or None)
if form.is_valid():
print("The form is valid!")
user = form.save(commit=False)
user_passsword = form.cleaned_data.get('password')
user.set_password(user_password)
user.save()
return render(request, 'blog/post/list.html', { 'user': user, 'title': title })
else:
print("The form is not valid!")
form = UserRegistrationForm()
return render(request, 'oauth/user/registration_form.html', { 'form': form, 'title': title })
請幫幫忙!我只是不知道自己出錯的地方 - 我所嘗試的一切似乎都給了我「形式無效!」在終端 - 我只是無法驗證這個補償形式。我錯過了什麼? (它必須是明顯的東西):(
1)你可以看到'form.errors'驗證錯誤,2)當您重新呈現頁面時,不要返回空白窗體('form = UserRegistrationForm()'),因爲沒有任何錯誤會通過(這是一個沒有數據的新窗體)。將無效的表單放入上下文中('form = UserRegistrationForm(request.POST or None)')。 –
似乎是發佈數據缺少相關數據來填寫必填字段。正如@JensAstrup提到的,嘗試使用'form.errors'進行調試。它會給你'強制'和'缺少'領域。 – cutteeth