Why am I getting form is invalid error in django?

django forms
django form validation
django messages
django form hidden field
django print form errors
django get form data
django-crispy-forms
styling django forms

During development of website in Django web framework I am getting form is invalid error when validating form.

I have searched online for solution but not able to solve my problem.

My files are as below.

models.py

class Customer(models.Model):
    f_name = models.CharField(max_length = 30, null=True)
    last_name = models.CharField(max_length = 30, null= True)
    cont_no = models.CharField(max_length = 30, null= True)
    pincode = models.IntegerField(default=0)
    def __str__(self):
        return self.f_name

class Product(models.Model):
    name = models.CharField(max_length = 30, null= True)
    uniq_price = models.IntegerField(default=0) 
    def __str__(self):
        return self.name

class Order(models.Model):
    cust_name = models.ForeignKey(Customer,related_name='first_name', on_delete=models.CASCADE)
    prod_name = models.ForeignKey(Product, related_name='uniqe_price', on_delete=models.CASCADE)
    unit_price = models.IntegerField(default=0)
    quantity = models.IntegerField(default=0)
    total = models.IntegerField(default=0)

forms.py

class CustomerForm(forms.ModelForm):    
    class Meta:  
        model = Order  
        fields = "__all__"

views.py

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

        form.save() 
        return redirect("place_ord")                        

    else:
        form = CustomerForm()

home.html

 <form id="myForm" action="{% url 'add_order' %}" method="POST">
      {% csrf_token %}
      <h1>add order</h1>

      <label>Customer</label>
      <select id="custs" name="customer">
        <option value="">Select Customer</option>                    
        {% for cust in customers %}
          <option id="{{ cust.id }}" value="{{ cust.f_name }}">
                {{ cust.f_name }}
          </option>
        {% endfor %}
       </select><br><br>
       <label>Product</label>
        <select id="singleSelectTextDDJS" name="prods" onchange="singleSelectChangeText()">
        <option>Select Product</option>                    
        {% for prod in products %}
          <option value="{{ prod.uniq_price }}">
              {{ prod.name }}
          </option>
        {% endfor %}
       </select><br><br>
       <label>Price:</label>
      <input type="text" name="price" class="Pric" id="textFieldTextJS" readonly=""><br><br>

      Qualitys:<input type="number" id="qty" class="qtys" name="quality"><br><br>

      Total price:<input type="text" name="totals" class="totals" id="total" readonly="">
      <br><br>
      <button type="submit" name="submit">place order</button>       
    </form>

Error

File "C:\Python37\lib\site-packages\django\forms\models.py", line 453, in save
    'created' if self.instance._state.adding else 'changed',
ValueError: The Order could not be created because the data didn't validate.

I am not able to validating my form & could anyone guide me what am I doing wrong ?


Problem is with your options that you have given in your form.

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>

The value is not validating with select fields. Try to put only valid values in all options.

Form and field validation | Django documentation, For an integer foreign key, this takes form of a ValueError thrown by the int function. formset.is_valid() File "/home/tim/code/django/django/forms/formsets.​py", line The user, seeing this error message, would not be able to fix it because the  I recently added a ChoiceField to my form but now it always returns invalid; I verified this with a 'print(form.is_valid())'. All fields are displayed properly in my template and values are always being passing so I can't fathom why the form is returned as invalid.


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')

refer this

Working with forms | Django documentation, Once the server gets a request with all valid form data, it can perform an (once validated) the error messages associated with invalid fields. December 31, 2017 Django Leave a comment. Questions: I am writing a Django application that has a model for People, and I have hit a snag. I am assigning Role objects to people using a Many-To-Many relationship – where Roles have a name


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})

#22229 (Invalid data can cause InlineFormSet.is_valid to throw , DjangoModelFormMutation getting "an invalid keyword argument for Mutation" error instead of model form errors #922. Closed. Aljabri-Salman  Note that any errors raised by your Form.clean() override will not be associated with any field in particular. They go into a special “field” (called __all__), which you can access via the non_field_errors() method if you need to. If you want to attach errors to a specific field in the form, you need to call add_error().


Django Tutorial Part 9: Working with forms, forms in my previous post. We will now discuss in detail the validation of form data. else: messages.error(request, 'The form is invalid.') return render(request​  GET and POST ¶. GET and POST are the only HTTP methods to use when dealing with forms.. Django’s login form is returned using the POST method, in which the browser bundles up the form data, encodes it for transmission, sends it to the server, and then receives back its response.


DjangoModelFormMutation getting "an invalid keyword argument for , This document covers the gritty details of Django's forms API. In this case, subject is blank (an error, because all fields are required by default) and sender is not a valid email You can access errors without having to call is_valid() first. Ideally Form.errors would have stored ValidationError instances and methods with an as_ prefix could render them, but it had to be done the other way around in order not to break code that expects rendered error messages in Form.errors.


Django Form Customization and Validation, I am always getting - form.is_valid returning False. kindly check where I am doing print(form.errors) return HttpResponse("Form is invalid!"). (I think) it basically fails to validate after I submit the formset (when inserting a score) I end up on the form_invalid path (and url consequently, this is why I am guessing the problem is the validation).