I want to make sure users fill all the fields before they are redirected to the next page. And if they don’t fill the fields it should raise an error telling them to fill the fields before they proceed. So to do that, I wrote the codes below. But the problem I’m facing is that when I didn’t fill the fields, it took me to the next page, instead of it to return me to the same page, and it didn’t raise any error.
How can I make it validate those fields before taking users to the next page?
Models
from django.core.exceptions import ValidationError
class Memb(models.Model):
slug=models.CharField(max_length=100)
member=models.CharField(max_length=100)
def __unicode__(self):
return self.member, self.slug
def clean_slug(self):
data=self.cleaned_data['slug']
if "Testy" not in data:
raise ValidationError("Enter the correct name for this field")
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('/good/')
else:
form=MembForm()
return render_to_response('member.html',{'MembForm':MembForm}, context_instance=RequestContext(request))
Template
{% block content %}
<form action="" method="POST">
{{MembForm.as_p}}
<input type="submit" value="Add"/>
</form>
{% endblock %}
There’s a few issues here, but your biggest issue is your view:
Views
Taking out the if else block:
What happens here is, it checks to see if the form is valid. But, no matter if it is valid or not, you still return /good/. This is probably not what you intended to do.
What you want to do is this:
of course, this can be consolidated together with your code below, so all you really need is:
A few other things I noticed:
You don’t need to explicitly define fields when using a model form. It’s the whole point of using them 😉 There are times to do this, and there are times to exclude them, but in your example I don’t see it.
I’m also not sure what the method “clean_slug” is getting you that the default functionality doesn’t do better. But, this could just be a snippet.
Finally, you are redirecting to a page called “good”. This is going to be the same no matter what the user enters, you should ask yourself if this is desired behavior. You may want to redirect to something like /good/(someuniqueid)/