×
   ❮   
PYTHON FOR DJANGO DJANGO FOR BEGINNERS DJANGO SPECIFICS PAYMENT INTEGRATION API BASICS Roadmap
     ❯   

DJANGO FORMS

Form creation

Creating Django Forms

Forms in Django provide a powerful way to handle user input, validation, and submission processing. Django's form handling system simplifies the creation of forms while also managing common tasks such as validation and error handling.

Overview

In Django, forms can be created either manually or by using built-in form classes. These forms are used to collect user input in a structured way, and Django automatically handles form rendering, validation, and security measures.

Basic Form Creation

To create a form in Django, you can define a class that inherits from forms.Form. You can then define fields that correspond to the data you want to collect from users.

Example

from django import forms

class ContactForm(forms.Form):
    name = forms.CharField(max_length=100)
    email = forms.EmailField()
    message = forms.CharField(widget=forms.Textarea)

Explanation: In this example, we create a ContactForm class that defines three fields: name, email, and message. The form fields use Django's built-in field types such as CharField and EmailField.

Rendering Forms in Templates

To render a form in a Django template, you can pass the form object to the template and use the template tags to display the form fields. Django automatically adds the required HTML for each field, including labels and validation messages.

Example Template


<form method="post"> 
 {% csrf_token %} 
 {{ form.as_p }} 
 <button type="submit">
Submit
</button>
</form>

Explanation: In this template, the form is rendered using {{ form.as_p }}, which outputs each form field wrapped in a paragraph tag. You can also use {{form.as_table}} or {{form.as_ul}} for different layouts.

Processing Form Data

Once the form is submitted, you need to process the data in the view. You can check whether the form is valid, and if so, you can access the cleaned data to use it in your application.

Example View

from django.shortcuts import render
from .forms import ContactForm

def contact_view(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            # Process the form data
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            message = form.cleaned_data['message']
            # Add further logic such as sending an email
    else:
        form = ContactForm()
    return render(request, 'contact.html', {'form': form})

Explanation: In this view, we handle form submissions by checking if the request is a POST request. If it is, the form is validated, and the cleaned data is accessed using form.cleaned_data. If the form is not submitted, an empty form is rendered.

Summary

Creating forms in Django involves defining form classes, rendering them in templates, and processing the data in views. Django's form system takes care of many repetitive tasks, such as validation and security, allowing developers to focus on business logic.


References


Django-tutorial.dev is dedicated to providing beginner-friendly tutorials on Django development. Examples are simplified to enhance readability and ease of learning. Tutorials, references, and examples are continuously reviewed to ensure accuracy, but we cannot guarantee complete correctness of all content. By using Django-tutorial.dev, you agree to have read and accepted our terms of use , cookie policy and privacy policy.

© 2024 Nischal Lamichhane. All Rights Reserved.
Django-tutorial.dev is styled using Bootstrap 5.
And W3.CSS.