2016-10-07 94 views
0

我正在建立一個註冊表格,但我在驗證時遇到了一些麻煩。Django表單驗證,如何在字段上顯示消息?

我想看到顯示在外地了錯誤信息,而是我在瀏覽器上得到一個錯誤說:

The User could not be created because the data didn't validate. 

Request Method:  POST 
Request URL: http://127.0.0.1:8000/account/register/ 
Django Version:  1.9.8 
Exception Type:  ValueError 
Exception Value:  

The User could not be created because the data didn't validate. 

Exception Location:  C:\Python34\lib\site-packages\django\forms\models.py in save, line 446 

這是我forms.py

class UserRegistrationForm(forms.ModelForm): 
    password = forms.CharField(label='Password', required=False ,widget=forms.PasswordInput) 
    password2 = forms.CharField(label='Repeat password', required=False ,widget=forms.PasswordInput) 

    class Meta: 
     model = User 
     fields = ('username', 'first_name', 'email') 

    def clean_password2(self): 
     password1 = self.cleaned_data.get('password1') 
     password2 = self.cleaned_data.get('password2') 
     #cd = self.cleaned_data 
     if not password2: 
      raise forms.ValidationError("Fill out the password2 .") 
     if password1 != password2: 
      raise forms.ValidationError("The two password fields didn't match.") 
     return password2 

這是我的觀點註冊

def register(request): 
    if request.method == 'POST': 
     user_form = UserRegistrationForm(request.POST) 
     if user_form.is_valid: 
      new_user = user_form.save(commit=False) 
      new_user.set_password(user_form.cleaned_data['password']) 
      new_user.save() 
      return render(request, 'account/register_done.html', {'new_user': new_user}) 
     else: 
      print (user_form.errors) 
    else: 
     user_form = UserRegistrationForm() 
    return render(request, 'account/register.html', {'user_form': user_form}) 

我HTMLS - register.html

{% extends "account/base.html" %} 
{% block title %}Create an account{% endblock %} 
{% block content %} 
    <h1>Create an account</h1> 
    <p>Please, sign up using the following form:</p> 
    <form action="." method="post"> 
     {{ user_form.as_p }} 
     {% csrf_token %} 
     <p><input type="submit" value="Create my account"></p> 
    </form> 
{% endblock %} 

register_done.html

{% extends "account/base.html" %} 
{% block title %}Welcome{% endblock %} 
{% block content %} 
    <h1>Welcome {{ new_user.first_name }}!</h1> 
    <p>Your account has been successfully created. Now you can <a href="{% url "login" %}">log in</a>.</p> 
{% endblock %} 
+0

我不知道你爲什麼重新發明輪子,你可以使用django-redux軟件包 – shining

+0

我正在關注一本書,我從django開始,所以在完成本書之後,我會去打包。 –

+0

這聽起來不錯,無論如何,你要跟隨哪本書? – shining

回答

2

好像你是不是叫is_valid方法,這可能會導致此問題:

if user_form.is_valid 

嘗試上述行更改爲:

if user_form.is_valid()

+0

謝謝哥們!我真的錯過了! –

+0

沒問題:)祝你好運! –

相關問題