why am i getting form is invalid error in django?

  • Last Update :
  • Techknowledgy :

value should be the pk of that object. ex -

 <select id="custs" name="customer">
        <option value="">Select Customer</option>                    
        {% for cust in customers %}
          <option id="cust_{{ cust.id }}" value="{{cust.pk}}">
                {{ cust.f_name }}
          </option>
        {% endfor %}
       </select>

You have to check whether your form is valid before saving it:

def add_order(request):
   if request.method == "POST":

   form = CustomerForm(request.POST)
if form.is_valid():
   form.save()
return redirect("place_ord")
else:
   print(form.errors)
else:
   form = CustomerForm()
return render(request, template, {
         'form': form ')

A more elegant form handler:

def add_order(request):
   form = CustomerForm(request.POST or None)
if form.is_valid():
   form.save()
return redirect("place_ord")
return render(request, 'myapp/form.html', {
   'form': form
})

Suggestion : 2

The validate() method on a Field handles field-specific validation that is not suitable for a validator. It takes a value that has been coerced to a correct datatype and raises ValidationError on any error. This method does not return anything and shouldn’t alter the value. You should override it to handle validation logic that you can’t or don’t want to put in a validator.,The validate() method on a Field handles field-specific validation that is not suitable for a validator. It takes a value that has been coerced to a correct datatype and raises ValidationError on any error. This method does not return anything and shouldn’t alter the value. You should override it to handle validation logic that you can’t or don’t want to put in a validator. ,The run_validators() method on a Field runs all of the field’s validators and aggregates all the errors into a single ValidationError. You shouldn’t need to override this method.,The run_validators() method on a Field runs all of the field’s validators and aggregates all the errors into a single ValidationError. You shouldn’t need to override this method.

# Good
ValidationError(_('Invalid value'), code = 'invalid')

# Bad
ValidationError(_('Invalid value'))
# Good
ValidationError(
   _('Invalid value: %(value)s'),
   params = {
      'value': '42'
   },
)

# Bad
ValidationError(_('Invalid value: %s') % value)
# Good
ValidationError(
   _('Invalid value: %(value)s'),
   params = {
      'value': '42'
   },
)

# Bad
ValidationError(
   _('Invalid value: %s'),
   params = ('42', ),
)
# Good
ValidationError(_('Invalid value'))

# Bad
ValidationError('Invalid value')
raise ValidationError(
   _('Invalid value: %(value)s'),
   code = 'invalid',
   params = {
      'value': '42'
   },
)
ValidationError(_('Invalid value: %s') % value)

Suggestion : 3

Problem is with your options that you have given in your form.,Why am I getting form is invalid error in django?,Getting an assertion error while views testing using invalid data in django,The value is not validating with select fields. Try to put only valid values in all options.

value should be the pk of that object. ex -

 <select id="custs" name="customer">
        <option value="">Select Customer</option>                    
        {% for cust in customers %}
          <option id="cust_{{ cust.id }}" value="{{cust.pk}}">
                {{ cust.f_name }}
          </option>
        {% endfor %}
       </select>

You have to check whether your form is valid before saving it:

def add_order(request):
   if request.method == "POST":

   form = CustomerForm(request.POST)
if form.is_valid():
   form.save()
return redirect("place_ord")
else:
   print(form.errors)
else:
   form = CustomerForm()
return render(request, template, {
         'form': form ')

A more elegant form handler:

def add_order(request):
   form = CustomerForm(request.POST or None)
if form.is_valid():
   form.save()
return redirect("place_ord")
return render(request, 'myapp/form.html', {
   'form': form
})

Suggestion : 4

Last modified: Aug 15, 2022, by MDN contributors

<form action="/team_name_url/" method="post">
   <label for="team_name">Enter name: </label>
   <input id="team_name" type="text" name="name_field" value="Default name for team.">
   <input type="submit" value="OK">
</form>
from django
import forms

class RenewBookForm(forms.Form):
   renewal_date = forms.DateField(help_text = "Enter a date between now and 4 weeks (default 3).")
import datetime

from django
import forms

from django.core.exceptions
import ValidationError
from django.utils.translation
import gettext_lazy as _

class RenewBookForm(forms.Form):
   renewal_date = forms.DateField(help_text = "Enter a date between now and 4 weeks (default 3).")

def clean_renewal_date(self):
   data = self.cleaned_data['renewal_date']

# Check
if a date is not in the past.
if data < datetime.date.today():
   raise ValidationError(_('Invalid date - renewal in past'))

# Check
if a date is in the allowed range(+4 weeks from today).
if data > datetime.date.today() + datetime.timedelta(weeks = 4):
   raise ValidationError(_('Invalid date - renewal more than 4 weeks ahead'))

# Remember to always
return the cleaned data.
return data
urlpatterns += [
path('book/<uuid:pk>/renew/', views.renew_book_librarian, name='renew-book-librarian'),
   ]
import datetime

from django.shortcuts
import render, get_object_or_404
from django.http
import HttpResponseRedirect
from django.urls
import reverse

from catalog.forms
import RenewBookForm

def renew_book_librarian(request, pk):
   book_instance = get_object_or_404(BookInstance, pk = pk)

# If this is a POST request then process the Form data
if request.method == 'POST':

   # Create a form instance and populate it with data from the request(binding):
   form = RenewBookForm(request.POST)

# Check
if the form is valid:
   if form.is_valid():
   # process the data in form.cleaned_data as required(here we just write it to the model due_back field)
book_instance.due_back = form.cleaned_data['renewal_date']
book_instance.save()

# redirect to a new URL:
   return HttpResponseRedirect(reverse('all-borrowed'))

# If this is a GET(or any other method) create the
default form.
else:
   proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks = 3)
form = RenewBookForm(initial = {
   'renewal_date': proposed_renewal_date
})

context = {
   'form': form,
   'book_instance': book_instance,
}

return render(request, 'catalog/book_renew_librarian.html', context)
book_instance = get_object_or_404(BookInstance, pk = pk)

# If this is a GET(or any other method) create the
default form
else:
   proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks = 3)
form = RenewBookForm(initial = {
   'renewal_date': proposed_renewal_date
})

context = {
   'form': form,
   'book_instance': book_instance,
}

return render(request, 'catalog/book_renew_librarian.html', context)

Suggestion : 5

Last Updated : 20 Jan, 2022

After creating the data models, the changes need to be reflected in the database to do this run the following command:
 

python manage.py makemigrations

Doing this compiles the models and if it didn’t find any errors then, it creates a file in the migration folder. Later run the command given below to finally reflect the changes saved onto the migration file onto the database.
 

python manage.py migrate

Till now, the data models and the Form class are defined. Now the focus will be on how these modules, defined above, are actually used.
First, run on localhost through this command 
 

python manage.py runserver