How to Fetch Data from Template Forms to Views in Django

In this tutorial, we’ll see how we can fetch text/data from HTML forms in our templates to views.py to process it and then send that data to another html page.

Before starting, let’s have a look on our project folder that what files we have and in what directory these files are stored.

How to Fetch Data from Template Forms to Views in Django 1

Here we’ve home.html in our templates and views.py in my_website directory in our project folder. Here home.html is our homepage and the path of templates has been already set in our settings.py.

Now you’ve the basic idea of our project files and directories so let’s see how to fetch data in our views.py from home.html and send that data to another HTML page named as newpage.html after processing it.

home.html  

How to Fetch Data from Template Forms to Views in Django 2

Here we have a form having a text area and a submit button. When user will press that button named as fetch data then his request will be redirected to the urls.py and look for the name my_function as mentioned in action attribute of form in above HTML page. 

urls.py

Here we’ve a path for the name my_function. Here we have a new page url newpage/ and a function views.new_page, so the request will be redirected to the function views.new_page

views.py

Now here we’ve a function new_page which receives user request and in next line we’re retrieving the text entered in our home.html form. Here we’re using the request object’s GET method to get the text from our textarea in our html form. All we have to do is just pass the name of our textarea inside the square brackets of GET method. Now we’ve all the text entered by the user inside our data variable. So now we can process or do any thing with our string variable data (like counting words, counting frequency of each word, replacing specific words, fetching entered email or phone numbers and all the operations that we can perform with strings in Python). But here we’re simply returning our information to a new html page named as newpage.html.

newpage.html

Here we’ve a simple heading New page and printing the value of the key data that is sent from our views.py’s new_page function.

Here’s the complete output of this project.

How to Fetch Data from Template Forms to Views in Django 3

Pressing fetch data button.

How to Fetch Data from Template Forms to Views in Django 4

That’s all.

I hope, now you’ve the basic idea of retrieving information from the HTML form to views to process it and also how to send the information from views to HTML document.

If you’ve any query related to this tutorial then please let us know in comment box.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.