django form field validation and error display

240 views
Skip to first unread message

赵飞

unread,
Jan 7, 2015, 9:03:09 AM1/7/15
to django...@googlegroups.com
I want to make a signup page just like:

When user click signup, I want to check the if the two password are the same, when not, give a error message after "confirm password".  Here is my code:

forms.py

class SignupForm(forms.Form):
    username
= forms.CahrField(
        label
=_("username"),
        max_length
=30,
   
)

    email
= forms.EmailField(label=_('email'),)
    password_1
= forms.CharField(
        label
=_("password"),
        widget
=forms.PasswordInput,
   
)
    password_2
= forms.CharField(
        label
=_("password_confirmed"),
        widget
=forms.PasswordInput,
   
)

   
def clean_password_2(self):
        password_1
= self.cleaned_data.get("password_1")
        password_2
= self.cleaned_data.get("password_2")
       
if password_1 and password_2 and password_1 != password_2:
           
raise forms.ValidationError(_('password confirm failed'))
       
return password_2

signup.html

<form method="post" action="{% url 'accounts:signup_post' %}">
    {% csrf_token %}
   
<table>
    {% for field in form %}
       
<tr>
           
<td>{{ field.label_tag }}</td>
           
<td>{{ field }}</td>
           
<td>{{ field.errors }}</td>
       
</tr>
    {% endfor %}
   
</table>

   
<input type='submit' id="submit" value={% trans "signup" %}>
   
<a href="{% url 'accounts:login' %}">{% trans "Already have accounts?" %}</a>
</form>


views.py

def signup_post(request):
   
if request.method == 'POST':
        signup_form
= forms.SignupForm(request.POST)

       
if signup_form.is_valid():
            signup_info
= signup_form.cleaned_data
            username
= signup_info['username']
            email
= signup_info['email']
            password
= signup_info['password_1']
            user
= User.objects.create_user(
                username
=username,
                email
=email,
                password
=password)
            user
.save()
           
# redirect to main page(not written so far)
       
else:
           
# I guess something wrong here, but no idea how to fix it.
           
return redirect(reverse("accounts:signup"))

   
else:
        signup_form
= forms.SignupForm()

   
return render(reverse("accounts:signup"), {'form': signup_form})

Can anyone help me out? 
Thanks!

James Schneider

unread,
Jan 7, 2015, 1:13:46 PM1/7/15
to django...@googlegroups.com
You should remove the inner else: clause and the redirect() line. If is_valid() fails, the last return statement will be used, which will pass along the bound form in signup_form that was snagged inside of your first if statement. Mimic the behavior here: https://docs.djangoproject.com/en/1.7/topics/forms/#the-view

BTW, django.shortcuts.redirect should handle the reverse() for you, so you can take that out to make your code a bit cleaner. Also, not sure if this is a copy/paste issue, but I think render() requires that request be sent along as the first argument, although I don't use FBV's, so don't quote me on that.

-James

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/d969fed6-5041-4093-aa35-35d611993cd3%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

赵飞

unread,
Jan 8, 2015, 4:34:07 AM1/8/15
to django...@googlegroups.com
I want to make a signup page, when user click signup, it will check if the two password are the same, when not, give a error message after "confirm password". 

But when I call "return render(request, reverse("accounts:signup"), {'form': signup_form}) " in my views.py, it shows me an error, the traceback is:

 Environment:

    Request Method: POST
   Request URL: http://127.0.0.1:8000/accounts/signup_post/
   
   Django Version: 1.7
   Python Version: 2.7.5
   Installed Applications:
   ('django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'accounts')
   Installed Middleware:
   ('django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware')
   
   Template Loader Error:
   Django tried loading these templates, in this order:
   Using loader django.template.loaders.filesystem.Loader:
   Using loader django.template.loaders.app_directories.Loader:
   
   Traceback:
   File "/Users/feizhao/.virtualenvs/nahan/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
     111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
   File "/Users/feizhao/dropbox/nahan/accounts/views.py" in signup_post
     64.     return render(request, reverse("accounts:signup"), {'form': signup_form})
   File "/Users/feizhao/.virtualenvs/nahan/lib/python2.7/site-packages/django/shortcuts.py" in render
     48.     return HttpResponse(loader.render_to_string(*args, **kwargs),
   File "/Users/feizhao/.virtualenvs/nahan/lib/python2.7/site-packages/django/template/loader.py" in render_to_string
     170.         t = get_template(template_name, dirs)
   File "/Users/feizhao/.virtualenvs/nahan/lib/python2.7/site-packages/django/template/loader.py" in get_template
     144.     template, origin = find_template(template_name, dirs)
   File "/Users/feizhao/.virtualenvs/nahan/lib/python2.7/site-packages/django/template/loader.py" in find_template
     136.     raise TemplateDoesNotExist(name)
   
   Exception Type: TemplateDoesNotExist at /accounts/signup_post/
   Exception Value: /accounts/signup/

my account app looks like:

   $ tree -L 3 accounts
   accounts
   ├── __init__.py
   ├── admin.py
   ├── forms.py
   ├── locale
      └── zh_CN
   ├── migrations
      ├── 0001_initial.py
      ├── __init__.py
   ├── models.py
   ├── static
      └── accounts
          └── login.css
   ├── templates
      └── accounts
          ├── base.html
          ├── login.html
          └── signup.html
   ├── tests.py
   ├── urls.py
   ├── views.py

 urls.py:

    urlpatterns = patterns(
       '',
       url(r'^accounts/', include('accounts.urls', namespace="accounts")),
       url(r'^admin/', include(admin.site.urls)),
   )

accounts/urls.py:

    urlpatterns = patterns(
       '',
       url(r'^login/$', views.login, name='login'),
       url(r'^signup/$', views.signup, name='signup'),
       url(r'^login_post/$', views.login_post, name='login_post'),
       url(r'^signup_post/$', views.signup_post, name='signup_post'),
   )

signup_post function in views.py: 

    def signup_post(request):
       if request.method == 'POST':
           signup_form = forms.SignupForm(request.POST)
   
           if signup_form.is_valid():
               signup_info = signup_form.cleaned_data
               username = signup_info['username']
               email = signup_info['email']
               password = signup_info['password_1']
               user = User.objects.create_user(
                   username=username,
                   email=email,
                   password=password)
               user.save()
   
       else:
           signup_form = forms.SignupForm()
   
       return render(request, reverse("accounts:signup"), {'form': signup_form})

I have read [Django TemplateDoesNotExist][1] and other similar questions, but no help!


在 2015年1月7日星期三UTC+8下午10时03分09秒,赵飞写道:

James Schneider

unread,
Jan 8, 2015, 6:11:02 AM1/8/15
to django...@googlegroups.com
Oh, you are passing a URL to render() instead of a template name. Try something like this:

return render(request, 'signup.html', {'form': signup_form})

Sorry, didn't catch that the first time.

-James


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.

赵飞

unread,
Jan 8, 2015, 6:29:52 AM1/8/15
to django...@googlegroups.com
That's it!  Thanks very very much, you help me a lot!

--
You received this message because you are subscribed to a topic in the Google Groups "Django users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-users/ZIsrf9vEXyg/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-users...@googlegroups.com.

To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.

For more options, visit https://groups.google.com/d/optout.



--
    


祝自由,开心!
----------------------------------------------------------------
中山大学
信息科学与技术学院
信息安全专业
赵飞
----------------------------------------------------------------

Edgar Gabaldi

unread,
Jan 8, 2015, 6:33:42 AM1/8/15
to django...@googlegroups.com
There is not your problem, but maybe will be in future. The best way to clean fields that depend of other fields is override the clean method of form.


赵飞

unread,
Jan 8, 2015, 6:39:18 AM1/8/15
to django...@googlegroups.com
I have read the doc, what you say is helpfull, thanks! 

在 2015年1月8日星期四UTC+8下午7时33分42秒,Edgar Gabaldi写道:
...
Reply all
Reply to author
Forward
0 new messages