Form Validation

6 views
Skip to first unread message

coded kid

unread,
Apr 15, 2012, 5:22:43 AM4/15/12
to Django users
I want my form to validate the fields so that only users who fill the
form field should be redirected to the next page. If a user fails to
fill any of the form field, the user should be taken to the same page
where it will output validation error so that the user can fill the
fields.

I tried writing these codes but it’s not working! Even if the user
didn’t fill the form field it will still redirect the user to the next
page which is not meant to be so.

Models.

class Memb(models.Model):
slug=models.CharField(max_length=100)
member=models.CharField(max_length=100)

def __unicode__(self):
return u"%s" % self.member

class MembForm(ModelForm):
class Meta:
model=Memb
fields=('slug','member')

Views:

def my_memb(request):
if request.method=="POST":
form=MembForm(request.POST)
if form.is_valid():
data=form.cleaned_data
form.save()
return HttpResponseRedirect('/test/')
else:
form=MembForm()
return render_to_response('member.html',
{'MembForm':MembForm}, context_instance=RequestContext(request))

Template:

{% extends "base.html" %}
{% block title %} Add Member {% endblock %}
{% block content %}
<form action="" method="POST">
{{MembForm.as_p}}
<input type="submit" value="Add"/>
</form>
{% endblock %}

How can I make sure the form validate before taking the user to the
next page? Kindly put me through. Thanks!

Daniel Roseman

unread,
Apr 15, 2012, 9:26:22 AM4/15/12
to django...@googlegroups.com
On Sunday, 15 April 2012 10:22:43 UTC+1, coded kid wrote:

def my_memb(request):
        if request.method=="POST":
                form=MembForm(request.POST)
                if form.is_valid():
                        data=form.cleaned_data
                        form.save()
                return HttpResponseRedirect('/test/')
        else:
                form=MembForm()
                return render_to_response('member.html',
{'MembForm':MembForm}, context_instance=RequestContext(request))


Take another look at the code above. If it's a POST, it checks the form's validity and if it's valid it saves. But the redirect is being executed whether or not the form is valid. It should be fairly clear how to fix that.
--
DR.
Reply all
Reply to author
Forward
0 new messages