nerdiplayboy
nerdiplayboy

Reputation: 556

django-why this form is always invalid

i have created a form with minimal fields(for testing) , but it never enters form.is_valid()

Here is the minimal code

in the models.py

 from django.db import models

 class sample(models.Model):
      field1=models.CharField(max_length=100)
      field2=models.CharField(max_length=100)

in the forms.py

from django.forms import ModelForm
from app.models import sample

class someform(ModelForm):
      class Meta:
        model=sample

in the views.py

some imports

def index(request):
    return render(request, 'app/index.html')

def contact(request):
    if request.method=='POST':
         form=someform(request.POST)
         if form.is_valid():
            field1=form.cleaned_data['field1']
            field2=form.cleaned_data['field2']
            return HttpResponse("valid")
         else:
            return HttpResponse("invalid")
    else:
            form=someform()
            return HttpResponse("error")

The problem is , it never enters (if form.is_valid()) . Am i missing something ? please help

in the index.html

<html>
      <body bgcolor="#2E9AFE">
      <form action="contact" method="post" enctype="multipart/form-data">
      {% csrf_token %}
      <input type="text" id="field1" name="field1">
      <input type="text" id="field2" name="field2">
      <input type="submit" id="submit" name="submit">
      </form></body></html>

Upvotes: 1

Views: 4187

Answers (2)

adamr
adamr

Reputation: 750

First pass your form to index.html, when the request is not POST in views.py:

else:
            form=someform()
            return render(request, 'index.html', locals())

In template you should make it like this:

<form action="contact" method="POST" xmlns="http://www.w3.org/1999/html">
    {% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="btn">Submit</button>
</form>

Upvotes: 4

Ricola3D
Ricola3D

Reputation: 2442

When receiving the POST query, Django is looking for the 2 fields of IDs id_field1 and id_field2, litteraly, thus your HTML is to be the following:

<html>
   <body bgcolor="#2E9AFE">
      <form action="contact" method="post" enctype="multipart/form-data">
        {% csrf_token %}
         <input type="text" id="id_field1" name="field1">
         <input type="text" id="id_field2" name="field2">
         <input type="submit" id="submit" name="submit">
         </form>
   </body>
</html>

Another solution is to use the {{ form.as_p }} or {{ form.as_table }} to render the inputs inside

or tags automatically.

You could also add {{ form.non_field_errors }}, {{ form.field1.errors }}, and {{ form.field2.errors }} in your current HTML to display the form errors when validation fails.

Upvotes: 3

Related Questions