Submit form data in Post method in Django

Django makes handling form submissions straightforward. In this guide, you’ll learn how to create a basic form that submits data using the POST method. We’ll cover how to set up a view to process the form data, create an HTML form template, and configure your URL routing. Follow along to see how easy it is to set this up.

Step-by-Step Guide

1.Create a View to Handle Form Submissions

In your Django app’s views.py, create a view function that handles both GET and POST requests. When the form is submitted, the view will process the form data.

from django.shortcuts import render
from django.http import HttpResponse

def contact_view(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        email = request.POST.get('email')
        message = request.POST.get('message')
        return HttpResponse(f"Thanks for your submission, {name}!")
    return render(request, 'form_template.html')

2.Create an HTML Template for the Form

Save the following code as from_template.html in your templates directory:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contact Form</title>
</head>
<body>
    <h1>Contact Us</h1>
    <form method="POST">
        {% csrf_token %}
        <label for="name">Name:</label>
        <input type="text" name="name" id="name" required>
        <br><br>
        <label for="email">Email:</label>
        <input type="email" name="email" id="email" required>
        <br><br>
        <label for="message">Message:</label>
        <textarea name="message" id="message" required></textarea>
        <br><br>
        <button type="submit">Submit</button>
    </form>
</body>
</html>

Explanation:

  • The <form> tag specifies method=”POST” which means the data will be sent using the POST method.
  • The {% csrf_token %} tag is important for security—it protects against Cross-Site Request Forgery attacks.
  • The form includes fields for the user’s name, email, and message.

3.Configure URL Routing

In your app’s urls.py, connect the view to a URL. This makes your form available at a specific web address.

# urls.py
from django.urls import path
from .views import contact_view

urlpatterns = [
    path('contact/', contact_view, name='contact'),
]

Explanation:

  • The URL route ‘contact/’ maps to the contact_view.
  • Now, visiting http://127.0.0.1:8000/contact/ in your browser will display the form, and submitting it will trigger the view to process the data.

Leave a Comment

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

Scroll to Top