Django Forms

What are Django Forms?

Django Forms: Every website, small or large needs to take input from the site visitors. A website will not complete unless it don’t take input from the user. This input can be in any form like placing orders, chatting, giving feedback, participations etc. Forms allows us to take input from the users. Like another content of page, forms also created using HTML.

django-forms
django-forms

Django forms contains some predefined functionality using libraries or modules.Basically Django Forms allows website to :

  • Automatic create HTML form.
  • Take input from the user.
  • Process the input.
  • Response back to the user.

Django forms advantages

Django facilitates various predefined functionalities, such as models, forms, validations etc. Forms are also one of them. I recommend you to use them because of following features:

  1. Quickly generate HTML form widgets.
  2. Validate data and process it into python data structure.
  3. Create form versions of our models(i.e Model Forms).
  4. Quickly update models from forms.

Process for creating Django forms

  1. The first thing we need to create is create an forms.py file inside the application.
  2. After that we will call Django’s built in form classes.
  3. Now, we need to show this form using views.py
  4. Then, we just add the views to the application’s URL , either directly or using include().
  5. After that, create the template folder along with the html file that will hold the template tagging for the forms.
  6. Place the context dictionary’s key inside the HTML <form> tag in templates.
  7. Now everything is setup. Once you have do so, you will see a very basic level form.
  8. Add CSRF token inside form tag, and you also can add bootstrap or crispy forms to design these forms.

Note

Remember to update the settings.py file to reflect the TEMPLATE_DIR variable. Also remember that your views should reflect sub-directories inside templates.

Django forms process

We have discussed a lot about creating forms. So, let’s start it!!!

Step 1: Create forms.py file inside app folder

project folder > app folder > forms.py

from django import forms

class MyForm(forms.Form):
    name = forms.CharField()
    email = forms.EmailField()
    Contact = forms.IntegerField()
    DOB = forms.DateField(widget = forms.DateInput(attrs={'type':'date'}))
    about = forms.CharField(widget = forms.Textarea())

Step 2: Show the form using views.py

project folder > app folder > views.py

from django.shortcuts import render
from myapp.forms import MyForm
def index(request):
    return render(request,'index.html')

def userForm(request):
    form = MyForm()
    return render(request,'form.html',{'uform':MyForm})

Step 3: Add the views to the application’s URL

project folder >project folder > urls.py

from django.contrib import admin
from django.urls import path, include
from myapp import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index,name='index'),
    path('form/',include('myapp.urls'))
]

project folder > app folder > views.py

from django.conf.urls import url
from myapp import views

urlpatterns = [
    url('',views.userForm,name='user_form')
]

Step 4: Setup HTML template for form

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>MyForm</title>
  </head>
  <body>
    <form method="post">
      {% csrf_token %}
      {{ uform.as_p }}
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

Output

Django Forms
Django Forms

What is HTTP, GET and POST?

HTTP stands for Hyper Text Transfer Protocol. It is designed to enable communication between  a client and server. The client submit request, the server then responds. The most commonly method used methods for this request/response are GET and POST.

GET requests data from a resource. Sometimes it referred as less secure because it shows data in URL of page. So it is risky to use GET method, where form contains password.

Where POST submits data to be process to a resource. It is secure as compare to GET. Because it transfers data without showing in URL of the page. It is mostly used in Django forms.

What is CSRF token?

It is an template tag that provides security protection against CSRF.

CSRF is an attack that may cause an website application to perform unwanted actions , the malicious websites may send an link to the user’s website and performs unwanted tasks using user’s credentials. csrf_token also protect from login csrf, that may login to user’s browser using someones credentials.

Syntax

   {% csrf_token %}
  • CSRF stands for Cross Site Request Forgery.
  • It is an attack which forces user to perform unwanted actions.
  • CSRF token secures HTTP POST action that is initiated on the subsequent submission of a form.
  • The Django form requires it to be present, if it is not there your form will not work.
  • It works by using a “hidden input” which is a random code and check that if it match the user’s  local site page.

Download source code

Download project on Github
Download project on Github 

So, it is all about today’s tutorial, we will discuss about form actions and styles in our further tutorials. Thanks!!!

14 thoughts on “Django Forms

Leave a Reply

Your email address will not be published. Required fields are marked *

  1. Hello, i read your blog occasionally and i own a similar one and i was just curious if you get a lot of spam feedback? If so how do you stop it, any plugin or anything you can recommend? I get so much lately it’s driving me crazy so any help is very much appreciated.

  2. Good site! I truly love how it is simple on my eyes and the data are well written. I am wondering how I could be notified whenever a new post has been made. I have subscribed to your RSS which must do the trick! Have a nice day!

  3. Hello there, just became alert to your blog through Google, and found that it’s really informative. I am going to watch out for brussels. I?ll appreciate if you continue this in future. A lot of people will be benefited from your writing. Cheers!

  4. A lot of thanks for your own work on this web site. Gloria take interest in carrying out research and it is easy to understand why. We all learn all concerning the compelling ways you make very helpful things by means of this website and even boost contribution from some other people on that topic while my daughter has been understanding a lot. Take advantage of the remaining portion of the new year. You have been carrying out a great job.

  5. Nice post. I be taught one thing more challenging on different blogs everyday. It should at all times be stimulating to read content from different writers and follow a little bit something from their store. I’d prefer to make use of some with the content on my blog whether or not you don’t mind. Natually I’ll offer you a hyperlink in your web blog. Thanks for sharing.

  6. I’m not sure why but this web site is loading very slow for me. Is anyone else having this issue or is it a issue on my end? I’ll check back later on and see if the problem still exists.

  7. Greetings I am so happy I found your weblog, I really
    found you by mistake, while I was looking on Bing for something else, Regardless
    I am here now and would just like to say thanks for a remarkable post and a all round interesting blog (I also love the theme/design),
    I don’t have time to look over it all at the moment but I have saved it and also
    added in your RSS feeds, so when I have time I will be
    back to read more, Please do keep up the superb work.

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.