Maitrey Prajapati
Maitrey Prajapati

Reputation: 11

Validating the form without required field in django 1.8

My django modelform is letting the user submit the form without raising error even when the user hasn't submitted appropriate form, here it lets the user keep the email field blank.It doesn't save into the database because of is_valid() but the page refreshes and form goes blank again... Here is the code

models.py

from django.db import models

class MainForm(models.Model):
    text = models.CharField(max_length=100)
    email = models.EmailField(blank=False)
    name = models.CharField(max_length=100,blank=False)


def __unicode__(self):
    return self.email

forms.py

from django import forms
from .models import MainForm,new_model


class form_MainForm(forms.ModelForm):
    class Meta:
        model = MainForm
        fields = '__all__'

views.py

def view_MainForm(request):

context = {
    "form": form_MainForm
}

if request.method == 'POST' :
    form_instance = form_MainForm(request.POST or None)
    if form_instance.is_valid():
        form_instance.save()
        return render(request,'done.html',{'text':form_instance.cleaned_data.get('email')})

return render(request,'main_form.html',context)

template ->main_form.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Main Form</title>
</head>
<body>


<form method="post" action=".">
{% csrf_token %}
{{ form.as_p }}
<input type="submit"  value="Submit">
</form>




</body>
</html>

Upvotes: 0

Views: 458

Answers (2)

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

Your view function is wrong - you have to pass the invalid form to the context to get the error messages, ie:

def view_MainForm(request):    
    if request.method == 'POST' :
        form_instance = form_MainForm(request.POST)
        if form_instance.is_valid():
            form_instance.save()
            # here you should redirect to avoid
            # re-submission of the form on page reload
            # cf https://en.wikipedia.org/wiki/Post/Redirect/Get
            return render(request,'done.html',{'text':form_instance.cleaned_data.get('email')})

    else:
        form_instance = form_MainForm()

    context = {"form": form_instance}
    return render(request,'main_form.html',context)

Upvotes: 1

rsb
rsb

Reputation: 420

check this link to render error in your form https://docs.djangoproject.com/en/1.10/topics/forms/#rendering-form-error-messages , this will give an idea like why you are not able to save data. when you are sending back the form it should be context = {"form": form_MainForm(request.POST)} , this will display the form submitted values

Upvotes: 0

Related Questions