Instagram
youtube
Facebook
Twitter

Django Forms

We can create HTML forms in Django by using the form class. It is similar to creating a Django model. Each field of the Django form directly maps to the HTML field. Let us understand the concept of Django forms by creating a user login form. 

 

Step 1: Create a forms.py file in your apps folder.

Step 2: Import forms from Django in your forms.py file by using the following expression.

from django import forms

Step 3: Now, I’m creating a login form therefore I am adding fields for the same. You can add fields according to your requirements.

  • AppName/forms.py
from django import forms

from django.contrib.auth.forms import UserCreationForm

from django.contrib.auth.models import User


class LoginForm(UserCreationForm):
        fields = ['username', 'password']

Here, first, I imported the forms from Django. Then I imported UserCreationForm from django.contrib.auth.forms. I also imported User from django.contrib.auth.models. After this, I created a class with the “LoginForm” name. The UserCreationForm written in brackets shows our form is a UserCreationForm. Then, I created a list containing a username & password.

Step 4: Create an HTML file for your Django Form in your templates folder.

  • AppName/templates
 
<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title> login </title> 
</head> 
<body>
<form method="POST" class="post-form"> 
        {% csrf_token %} 
        {{ form.as_p}} 
        <button type="submit" class="save btn btn-default">Save</button> 
</form> 
</body> 
</html>

Now, I have created an HTML template for my login form. I passed all fields and attributes of my form in the template by using the {{ form.as_p}} tag. Here as_p represents our form will be displayed as a paragraph. There are some more options to render our form.

  • {{ form.as_table }} - this will render the form as table cells wrapped in <tr> tags.
  • {{ form.as_p }} - this will render the form wrapped in <p> tags.
  • {{ form.as_ul }} - this will render the form wrapped in <li> tags.
  • {{ form.as_div }} -  will render the form wrapped in <div> tags.

 

In Django, there are mainly two HTTP methods to deal with forms. GET and POST methods. In my login form, I have used the post method.

GET Method - GET is an HTTP method that bundles the submitted data into a string and utilizes it to construct a URL. The URL includes the data keys, values, and the address to which the data will be sent.

POST Method - POST is also an HTTP 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.

 

Step 5: Django needs to know what to do with the user data after the user hits the submit button. We have to add those instructions in the view.py file.

from .forms import LoginForm
 
def contact(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            form.save()


    context = {'form': form}
    return render(request, "contact.html") 

First I imported LoginForm from forms.py file. Then, I created a function with my template file name. After this, I have given an “ if “ condition that will allow only POST methods. I have created another “ if “ condition that will check whether our form is valid or not. If our form is valid it will get saved in the database. I have also created a dictionary with my form name and passed it into the render. It will display the form.

we have done all the things now, let's check whether our form is working or not.

 

 

Our form is rendered successfully, let's check whether the data is saved in the database or not.

Working properly.