Templates now showing any errors in Django -
i have form registration. when try register, , fine, that, showing form validation errors in template, when there should be.
forms.py:
from django.contrib.auth.forms import usercreationform django.contrib.auth.models import user django import forms import re django.core.exceptions import objectdoesnotexist class usercreationform(usercreationform): class meta: model = user fields = ('first_name', 'last_name', 'username',) username = forms.emailfield(label='email', max_length=250) def save(self, commit=true): user = super(usercreationform, self).save(commit=false) user.email = user.username user.save() return user def clean_password2(self): if 'password1' in self.cleaned_data: password1 = self.cleaned_data['password1'] password2 = self.cleaned_data['password2'] if password1 == password2: return password2 raise forms.validationerror('password not match.') def clean_username(self): username = self.cleaned_data['username'] if not re.search(r'^\w[\w.]*@[\w.]+$', username): raise forms.validationerror('please enter valid email address.') try: user.objects.get(username=username) except objectdoesnotexist: return username raise forms.validationerror('email address taken.')
views.py:
def register_user(request): if request.method == 'post': form = usercreationform(request.post) if form.is_valid(): form.save() return httpresponseredirect('/accounts/register_success') else: print form.is_valid() print form.errors args = {} args.update(csrf(request)) args['form'] = usercreationform() print args return render_to_response('register.html', args)
register.html:
{% extends "base.html" %} {% block content %} <h1>registration:</h1> <form method="post" action="."> {% csrf_token %} {{form.as_p}} <input type="submit" value="register" /> </form> {% endblock %}
i tried {% if form.errors %}
:
{% extends "base.html" %} {% block content %} {% if form.errors %} <p>{{form.errors }}</p> {% endif %} <h1>registration:</h1> <form method="post" action="."> {% csrf_token %} {{form.as_p}} <input type="submit" value="register" /> </form> {% endblock %}
but no luck. think missing something.
the reason is, if there errors, overwriting form=usercreationform()
basically, if if form.is_valid()
false
, need send form unaltered. calling form=usercreationform
after form.is_valid()
overriding errors
try this:
def register_user(request): if request.method == 'post': form = usercreationform(request.post) if form.is_valid(): form.save() return httpresponseredirect('/accounts/register_success') else: print form.is_valid() print form.errors else: form = usercreationform() return render_to_response('register.html', {'form': form}, context_instance=requestcontext(request))
Comments
Post a Comment