Hello friends, welcome to Django Forms Tutorial. We already posted a couple of tutorials for Python Django Framework. Today we will learn how we can handle Forms in this Django Forms Tutorial.
If you are an absolute beginner in Python Django Framework, then follow the previously published post first. You can go to the previous posts from below links.
- Python Django Tutorial for Beginners – Getting Started
- Django Views Tutorial – Creating Your First View
- Django Templates Tutorial – Creating A Simple Template
Now let’s start this Django Forms Tutorial. I am assuming you are already aware of HTML forms.
Contents
Django Forms Tutorial
The first thing we will do is, we will create a new Django Project using the command django-admin startproject YourDjangoApp then we will open it in PyCharm.
Creating a new Project
- Open command prompt or PowerShell and navigate to the directory where you want to create your project.
- Now run the following command.
1 2 3 |
django-admin startproject FormExample |
- I created a project named FormExample, as you can see in the above command.
Creating Templates
I want to simplify this tutorial as much as I can. That is why in this post I will use two templates. From the first template I will take some values from the user, and in the second template we will display the received values. This way you will get the basic idea of how HTML form works in Django. And that is the primary motive of this Django Forms Tutorial. So let’s create our templates first.
- First create a templates folder in your project, as you can see in the below image.
- Now go to settings.py and define the templates folder path. Same, as we did in the earlier Django Templates Tutorial .
- Inside templates folder create an HTML file and name it anything. I just created index.html. And write the following HTML code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Django Forms Tutorial</title> </head> <body> <h2>Django Forms Tutorial</h2> <form method="post" action="/getdata/"> <table> <tr> <td>Enter your name:</td> <td><input type="text" name="name"/></td> </tr> <tr> <td>Enter your email:</td> <td><input type="email" name="email"/></td> </tr> <tr> <td>Enter your phone:</td> <td><input type="text" name="phone"/></td> </tr> <tr> <td> </td> <td> <button>Submit Form</button> </td> </tr> </table> </form> </body> </html> |
What we did?
Above we have created an HTML document. The document has an HTML form. We are using POST method in Form. And inside the action attribute we have given a URL /getdata/ we will define this URL in our urls.py file.
In form we have 3 fields name, email and phone that the user will enter.
- Now create one more HTML file inside templates folder. I just created showdata.html and write the following html code inside this file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Django Forms Tutorial</title> </head> <body> <h2>Django Forms Tutorial</h2> <form method="post" action="/getdata/"> <table> <tr> <td>Your Name</td> <td><strong>{{ name }}</strong></td> </tr> <tr> <td>Your Email</td> <td><strong>{{ email }}</strong></td> </tr> <tr> <td>Your Phone</td> <td><strong>{{ phone }}</strong></td> </tr> </table> </form> </body> </html> |
What we did?
Again we have created a simple HTML page. The page has a table that will display the data entered in the form we created. As I explained in the previous tutorial that for variables inside HTML form we write it inside {{ }}.
Creating View
Now we will create a view to handle our request.
- Inside your project create a new file views.py and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
#importing required packages from django.http import HttpResponse from django.template import loader from django.views.decorators.csrf import csrf_exempt #disabling csrf (cross site request forgery) @csrf_exempt def index(request): #if post request came if request.method == 'POST': #getting values from post name = request.POST.get('name') email = request.POST.get('email') phone = request.POST.get('phone') #adding the values in a context variable context = { 'name': name, 'email': email, 'phone': phone } #getting our showdata template template = loader.get_template('showdata.html') #returing the template return HttpResponse(template.render(context, request)) else: #if post request is not true #returing the form template template = loader.get_template('index.html') return HttpResponse(template.render()) |
If you are working with GET, replace POST with GET in the above code. And inside your HTML form change POST to GET.
What we did?
In the above code we are first disabling csrf. In django there is already a feature to prevent Cross Site Request Forgery (CSRF). But I wanted to make this tutorial as simple as possible so I just disabled csrf for now. using @csrf_exempt. (Read this Django Forms Example to know working without disabling csrf).
Then we defined our view index, inside the view we are first checking whether a POST request has came or not. If POST is true then we are getting values from POST. Then we are adding the values in another variable and passing it to our template. The same we did in the last Django Templates Tutorial.
And in the else part we are loading the same form template.
Defining URL Patterns
- Come inside urls.py file and modify it as follow.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
from django.conf.urls import url from django.contrib import admin #importing views #we need to create views.py from . import views urlpatterns = [ url(r'^admin/', admin.site.urls), #define the url getdata that we have written inside form url(r'^getdata/', views.index), #defining the view for root URL url(r'^$', views.index), ] |
- Now try executing your project. (python manage.py runserver) If you don’t know how to run django project read the previous tutorial Python Django Tutorial for Beginners.
- You will get the following results.
Bingo! our form is working absolutely fine. You can also download the source code from the below link.
Django Forms Tutorial Source Code (1596 downloads)
Next Post: Django Forms Example with Form Class
So that’s all for this Django Forms Tutorial friends. It was very basic form handling using Django. In upcoming tutorials, we will learn some cool features of Django with Forms. And feel free to submit any query regarding this Django Forms Tutorial. Thank You 🙂
Nice..
but how do I save the form content into the database
how to maintain database of this form sir tell us that also.
but your tutorials are just awsome
I am new to Python and Django & I read and surfing many tutorial for same but Khan Sir your tutorial are awesome and yes i also want to know how do I save the form content into the database in MySql as well as Sqlite
Thanks
i want this python with django complete course bro. when it ll be uploaded or just takes some time to be updated bro? pls reply
Thank you very much
When I run this code I am getting the following error
Exception Type:
UnicodeDecodeError
Exception Value:
‘utf-8’ codec can’t decode byte 0xa0 in position 43: invalid start byte
I think the error is in this line
template = loader.get_template(‘index.html’)
What is the solution for this
Try replace ‘ with ‘