Django Tutorial

Django Create A Complete Project

Django Template

Django Database Query

Django Form

Django Authentication and Permission Management

Django unittest

Django Advanced

Django Form API

Django is a powerful and versatile web framework for Python that makes it easy to create web applications quickly. One of its key features is the ability to handle and process forms. Django's Form API provides a convenient way to create, render, and validate form data.

In this tutorial, we'll cover:

  1. Creating a basic Django Form
  2. Rendering a form in a template
  3. Handling form submission and validation
  4. Customizing form rendering

Before we dive in, make sure you have Django installed on your system. If not, install it using pip:

pip install django

1. Creating a basic Django Form

First, let's create a basic Django Form. In your Django app, create a file named forms.py and add the following code:

from django import forms

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

This code creates a simple ContactForm with three fields: name, email, and message. We've used Django's built-in form fields (e.g., CharField, EmailField) and widgets (e.g., Textarea) to define these fields.

2. Rendering a form in a template

Next, let's create a template to render the form. In your app's templates folder, create a file named contact.html and add the following code:

{% for field in form %}
    <div class="form-group">
        <label for="{{ field.auto_id }}">{{ field.label }}</label>
        {{ field }}
    </div>
{% endfor %}

This code iterates through the form fields and renders them with their respective labels.

3. Handling form submission and validation

Now, let's create a view to handle the form submission and validation. In your app's views.py file, add the following code:

from django.shortcuts import render
from .forms import ContactForm

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            # Process the data in form.cleaned_data
            # ...
            return render(request, 'success.html')
    else:
        form = ContactForm()

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

This view creates a new instance of ContactForm and populates it with the submitted data if the request method is POST. It then checks if the form is valid by calling form.is_valid(). If the form is valid, you can process the data in form.cleaned_data. Otherwise, a new empty form is created.

Finally, add the corresponding URL pattern for the view in your app's urls.py file:

from django.urls import path
from . import views

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

4. Customizing form rendering

Django allows you to customize form rendering, which can help you achieve the desired look and feel for your form. For example, you can add Bootstrap classes to your form fields:

from django import forms

class ContactForm(forms.Form):
    name = forms.CharField(label="Name", max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'}))
    email = forms.EmailField(label="Email", widget=forms.EmailInput(attrs={'class': 'form-control'}))
    message = forms.CharField(label="Message", widget=forms.Textarea(attrs={'class': 'form-control'}))
  1. Creating forms in Django using Form API:

    • Description: Utilize Django's Form API to create HTML forms, simplifying the process of handling user input.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          name = forms.CharField(label='Your Name', max_length=100)
          email = forms.EmailField(label='Your Email')
          message = forms.CharField(label='Your Message', widget=forms.Textarea)
      
  2. Django form validation and handling:

    • Description: Implement form validation to ensure that user-submitted data meets specified criteria.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          # ... (fields definition)
      
          def clean_name(self):
              name = self.cleaned_data['name']
              if len(name) < 3:
                  raise forms.ValidationError('Name must be at least 3 characters long.')
              return name
      
  3. Django form widgets and fields:

    • Description: Explore Django form widgets and fields to tailor the input elements and their representation.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          date_of_birth = forms.DateField(widget=forms.SelectDateWidget)
      
  4. Form handling in Django views:

    • Description: Handle form submission in Django views, process the data, and perform appropriate actions.
    • Code Example:
      # views.py in your app
      from django.shortcuts import render
      from .forms import MyForm
      
      def my_view(request):
          if request.method == 'POST':
              form = MyForm(request.POST)
              if form.is_valid():
                  # Process valid form data
          else:
              form = MyForm()
      
          return render(request, 'my_template.html', {'form': form})
      
  5. Django ModelForm API usage:

    • Description: Use Django's ModelForm API to create forms based on Django models, simplifying the process of handling model instances.
    • Code Example:
      # forms.py in your app
      from django import forms
      from .models import MyModel
      
      class MyModelForm(forms.ModelForm):
          class Meta:
              model = MyModel
              fields = ['name', 'email', 'message']
      
  6. Django form templates and rendering:

    • Description: Render forms in Django templates and customize their appearance using template tags and filters.
    • Code Example:
      <!-- my_template.html -->
      <form method="post" action="{% url 'my_view' %}">
          {% csrf_token %}
          {{ form.as_p }}
          <button type="submit">Submit</button>
      </form>
      
  7. Django form handling in class-based views:

    • Description: Handle forms using Django's class-based views, providing a structured and reusable approach.
    • Code Example:
      # views.py in your app
      from django.views import View
      from django.shortcuts import render
      from .forms import MyForm
      
      class MyFormView(View):
          template_name = 'my_template.html'
      
          def get(self, request):
              form = MyForm()
              return render(request, self.template_name, {'form': form})
      
          def post(self, request):
              form = MyForm(request.POST)
              if form.is_valid():
                  # Process valid form data
              return render(request, self.template_name, {'form': form})