Creating Forms in Django

rohit20001221

rohit20001221

Posted on March 26, 2022

Creating Forms in Django

Hi guy's today i am going to show you how can we create forms in django

Step 1 : Setting up the django Project

Image description

create a django project using the following command

django-admin startproject DjangoForms

Step 2 : Creating a app in our project

  • fist cd into your project directory and type the following command

python manage.py startapp demo

Image description

Step 3 : Creating Forms 😄

creating a normal form

first let me show how to create a normal form (i.e this form is not connected to any of the models)

  1. create a file called forms.py in your app folder
  • we will be importing the froms from django using following code

  • from django import forms

  • every form in django will inherit the following class forms.Form

  • for example we will create a form called ContactForm as follows
    class ContactForm(forms.Form)

  • now lets add some fileds to our form

from django import forms
from django.core.validators import MaxLengthValidator

class ContactForm(forms.Form):
    name = forms.CharField()
    email = forms.EmailField()
    mobile = forms.CharField(
        validators=[MaxLengthValidator(10)]
    )
Enter fullscreen mode Exit fullscreen mode

we can use form.TypeField for the fields Type can be anything like Char, Email, Integer,Float etc ...

and also note that we are adding MaxLengthValidator to the validators of mobile field this ensures that when the form is submitted the length of value of mobile field is less than 10

  1. now lets create a view in views.py which will render the form
# views.py
from .forms import ContactForm

def contact_form(request):
    form = ContactForm() # <-- Initializing the form

    # sending the form to our template through context
    return render(request, "form.html", {"contactform": form})
Enter fullscreen mode Exit fullscreen mode

mapping the view to the urls.py

# urls.py of the project
from django.contrib import admin
from django.urls import path
from demo.views import contact_form

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', contact_form),
]

Enter fullscreen mode Exit fullscreen mode
  1. rendering the form in form.html

there are two ways to render the form in our template

  1. rendering using form.as_p
   <form method="POST" action="">
       {{form.as_p}}
       <button>submit</button>
   </form>
Enter fullscreen mode Exit fullscreen mode

run the development server using python manage.py runserver

if you navigate to http://localhost:8000 the form is displayed as shown below

Image description

handling the data submitted by the form

from django.shortcuts import render

# Create your views here.
from .forms import ContactForm

def contact_form(request):
    form = ContactForm() # <-- Initializing the form

    if request.method == 'POST':
        form = ContactForm(request.POST) # <-- populating the form with POST DATA

        if form.is_valid():  # <-- if the form is valid
            print("[**] data received [**]")  # <-- we handle the data 
            print(form.cleaned_data['name'])
            print(form.cleaned_data['email'])
            print(form.cleaned_data['mobile'])


    # sending the form to our template through context
    return render(request, "form.html", {"contactform": form})
Enter fullscreen mode Exit fullscreen mode

When the form is submitted successfully we see the data logged to terminal

# output in the terminal
March 26, 2022 - 20:06:02
Django version 3.0.7, using settings 'DjangoForms.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[**] data received [**]
blog
rohit20001221@gmail.com
9999999999
Enter fullscreen mode Exit fullscreen mode

but when the data entered in the forms is incorrect the error message is displayed

Image description

we can see the mobile number is more than 10 characters long so the error message is displayed in the form

Alternate way to render a form

render each field manually

<form method="POST" action="">{% csrf_token %} 
    <div>
        {{ form.name }}

        <!---Rendering the error message--->
        {% for error in form.name.error %}
            {{error}}
        {% endfor %}
    </div>
    <div>
        {{ form.email }}

         <!---Rendering the error message--->
        {% for error in form.email.error %}
            {{error}}
        {% endfor %}
    </div>
    <div>
        {{ form.phone }}

         <!---Rendering the error message--->
        {% for error in form.phone.error %}
            {{error}}
        {% endfor %}
    </div>
    <button>submit</button>
</form>
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
rohit20001221
rohit20001221

Posted on March 26, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Creating Forms in Django
django Creating Forms in Django

March 26, 2022