Open In App

Get Value from Form Field in Django Framework

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Django, getting data from a form field is a straightforward process, designed to ensure you manage user input securely and effectively.
To retrieve values from a form field in Django, you typically access the data in your view after form submission.

Get Value from Form Field in Django

To retrieve values from a form field in Django, we typically access the data in our view after form submission. Here’s how we do it:

  1. Define the Form: Create a form class using forms.Form or forms.ModelForm.
  2. Handling POST Request: In your view, check if the request method is POST.
  3. Instantiate the Form: Create an instance of the form using the data from request.POST.
  4. Validate the Form: Use form.is_valid() to validate the data.
  5. Access Form Data: If the form is valid, access the field data using form.cleaned_data['fieldname'], where 'fieldname' is the name of the field in the form.

Example Project Guide

we'll explore how to retrieve values from form fields in Django. We'll walk through a simple project to demonstrate the process, making it easy for us to understand and apply these concepts to our own Django applications.

Step 1: Setting Up the Project

First, create a virtual env a new Django project and app. We'll name the project myproject and the app myapp.

python -m venv venv
venv/Scripts/activate
pip install django

django-admin startproject myproject
cd myproject
python manage.py startapp myapp

Next, add myapp to the INSTALLED_APPS list in your settings.py file.

Step 2: Creating a Simple Form

In your myapp directory, create a forms.py file to define a simple contact form:

Python
from django import forms

class ContactForm(forms.Form):
    name = forms.CharField(label='Your Name', max_length=100)
    email = forms.EmailField(label='Your Email')
    message = forms.CharField(widget=forms.Textarea, label='Your Message')

Step 3: Creating the View to Handle Form Submission

In views.py, add a view to process the form data:

Python
from django.shortcuts import render, redirect
from .forms import ContactForm

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            message = form.cleaned_data['message']

            # Example of processing the data
            print(f"Name: {name}")
            print(f"Email: {email}")
            print(f"Message: {message}")

            return redirect('thanks')
    else:
        form = ContactForm()

    return render(request, 'contact.html', {'form': form})

Step 4: Creating the Template

Create a templates directory inside your myapp directory and add a contact.html file:

HTML
<!DOCTYPE html>
<html>
<head>
    <title>Contact Form</title>
</head>
<body>
    <h2>Contact Us</h2>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Send</button>
    </form>
</body>
</html>

This simple template renders the form and allows users to submit their details.

Step 5: Adding URL Patterns

In your myapp directory, create a urls.py file and add the following:

Python
from django.urls import path
from .views import contact

urlpatterns = [
    path('contact/', contact, name='contact'),
    path('thanks/', lambda request: HttpResponse('Thank you!'), name='thanks'),
]

Include this urls.py in your main urls.py file of the project:

Python
from django.urls import include, path

urlpatterns = [
    path('', include('myapp.urls')),
]

Step 6: Running the Project

Run the server using:

Navigate to http://127.0.0.1:8000/contact/ to see the form. Fill in the details and submit. You should see the data printed in the console, and then be redirected to a "Thank You" page.

Capture
Capture0

Conclusion

This simple project demonstrates how to get values from a form field in Django. By following these steps, you can effectively handle user input, validate it, and use it in your Django applications. This is a foundational skill for any Django developer, essential for building dynamic, user-driven web applications.


Article Tags :
Practice Tags :

Similar Reads