Django Form Processing | Django Forms Tutorial- W3Schools

Form creation in Django is similar to the creation of a model. Once you inherit the Django class in your code, its attributes will help you to create the form fields. For this, you need to start by adding the forms.py file in the myapp folder. This forms.py file will contain all your app forms. Here, we will begin by creating a login form.

Myapp/forms.py
#-*- coding: utf-8 -*-
from django import forms 
class LoginForm(forms.Form):
   user = forms.CharField(max_length = 100)
   password = forms.CharField(widget = forms.PasswordInput()) 

The above code clearly shows the use of argument named widget. This parameter is used for HTML rendering. In this case, we will be hiding our password instead of displaying it. There are several other widgets available in Django which are:

* DateInput for storing dates
* CheckboxInput for creating checkboxes

and many others.

How to Use A Form In A View?
Django supports two kinds of HTTP requests. One is GET and another is POST. In Django, the request object has an attribute called a method. This parameter is used to set the type of request. And to access the data passed through the POST, you need to make use of request.POST dictionary.

It’s time for you to create a login view under the myapp/views.py file –

#-*- coding: utf-8 -*-
from myapp.forms import LoginForm
def login(request):
   username = “not logged in”   
   if request.method == “POST”:
      #Get the posted form
      MyLoginForm = LoginForm(request.POST)      
      if MyLoginForm.is_valid():
         username = MyLoginForm.cleaned_data[‘username’]
   else:
      MyLoginForm = Loginform()
   return render(request, ‘loggedin.html’, {“username” : username})

The above code will display a login form which will be posted by using loggedin.html template. To check whether it is accurate or not, you need to match it with the login form template. This template will be saved under the name of login.html. 

<html>
   <body>      
      <form name = “form” action = “{% url “myapp.views.login” %}”
         method = “POST” >{% csrf_token %}         
         <div style = “max-width:470px;”>
            <center>
               <input type = “text” style = “margin-left:20%;”
                  placeholder = “Identifiant” name = “username” />
            </center>
         </div>
         <br>         
         <div style = “max-width:470px;”>
            <center>
               <input type = “password” style = “margin-left:20%;”
                  placeholder = “password” name = “password” />
            </center>
         </div>
         <br>         
         <div style = “max-width:470px;”>
            <center>             
               <button style = “border:0px; background-color:#4285F4; margin-top:8%;
                  height:35px; width:80%;margin-left:19%;” type = “submit”
                  value = “Login” >
                  <strong>Login</strong>
               </button>               
            </center>
         </div>         
      </form>      
   </body>
</html>

The above login.html will display the template for the login form. It will also post the result of the previous login view. The tag in the template is used to prevent the Cross Site Request Forgery (CSRF) attack on your website. This tag is: {% csrf_token %} 

Other than the login template, you also need to have access to loggedin.html template that will provide the after form treatment.

<html>   
   <body>
      You are : <strong>{{username}}</strong>
   </body>   
</html>

To finish off with this complete process, the last thing you need to do is to pair the URL to the newly created view. For this, open myapp/urls.py file where you are required to make the following changes.

from django.conf.urls import patterns, url
from django.views.generic import TemplateView
urlpatterns = patterns(‘myapp.views’,
   url(r’^connection/’,TemplateView.as_view(template_name = ‘login.html’)),
   url(r’^login/’, ‘login’, name = ‘login’))

To get the final output of the login.html template, type in the given URL: http://127.0.0.1:8000/myapp/connection/ in the web browser and you will land up on the below provided screen:

This is a valid login form template which made use of POST HTTP request. Make sure that you fill in both the required text fields and only then you will be redirected to the given web page.

In this case, we have logged in with the ‘polo’ username and we left the password field empty (which is as similar to ‘forgot the password’ option). The screen will look like the following with the displayed message ‘You are : not logged in’.

How to Use Your Own Form Validation?

Here, we will be considering the same example where we will be using the following code to validate our login form.

MyLoginForm.is_valid()

We have used self form validation engine offered by the Django itself. In this case, we are using it just to verify if the given text fields are mandatorily filled or not. Now, you just need to ensure whether the username you are trying to log in with is present in the Dreamreal database. To do this, you need to make alterations in the myapp/forms.py file as shown below:

#-*- coding: utf-8 -*-
from django import forms
from myapp.models import Dreamreal 
class LoginForm(forms.Form):
   user = forms.CharField(max_length = 100)
   password = forms.CharField(widget = forms.PasswordInput()) 
   def clean_message(self):
      username = self.cleaned_data.get(“username”)
      dbuser = Dreamreal.objects.filter(name = username)
      if not dbuser:
         raise forms.ValidationError(“User does not exist in our db!”)
      return username

The is_valid() method whenever called will give you a correct output. You will get the correct output only if the user is having its entry present in the database. In case you want to verify whether your desired text field is present on the form or not, you need to make use of the method beginning with “clean_”. After which you need to enter your field name to the form class. Make sure that you raise forms.ValidationError which is an important part of this last step.