Creating Forms in Django
Tags: django, python, coding, webdevelopmen
Published: 2022-03-26 20:19:58

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nq55y7jk2zfm6uk5hkfj.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kuifpdweib91cxcvvw3o.png)

## 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

```python
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)]
    )
```

> 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

2. **now lets create a view in `views.py` which will render the form**

```python
# 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})
```

**mapping the view to the urls.py**
```python
# 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),
]

```

3. **rendering the form in `form.html`**

there are two ways to render the form in our template

1. rendering using `form.as_p`

   ```html
   <form method="POST" action="">
       {{form.as_p}}
       <button>submit</button>
   </form>
   ```

**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2cg063i6n4gsdjbs54ac.png)

 
**handling the data submitted by the form**
```python
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})
```

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

```bash
# 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
```

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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rbt2y96p1pkrvc25ymix.png)

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

```html
<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>
```