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 System

In this Django Form System tutorial, we'll cover the basics of Django forms, including how to create, validate, and render forms.

  1. Creating a simple form
  2. Using the form in a view
  3. Rendering the form in a template
  4. Handling form submission and validation

1. Creating a simple form

Django provides a powerful form system that allows you to define and manage HTML forms easily. To create a simple form, create a new file called forms.py in your Django app folder 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)

In this example, we've created a ContactForm class that inherits from django.forms.Form. We defined three fields: name, email, and message, each with different form field classes.

2. Using the form in a view

Now, let's use the ContactForm in a view. In your app's views.py file, add the following code:

from django.shortcuts import render
from .forms import ContactForm

def contact(request):
    form = ContactForm()

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

In this example, we imported the ContactForm class and created an instance of the form in our view function. We then passed the form instance to our template context.

3. Rendering the form in a template

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

{% extends 'base.html' %}

{% block content %}
  <h2>Contact Us</h2>
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Send Message</button>
  </form>
{% endblock %}

In this example, we used the {{ form.as_p }} template tag to render the form as a series of paragraphs, with each field enclosed in a <p> element. You can also use {{ form.as_table }} to render the form as a table, or {{ form.as_ul }} to render it as a list.

4. Handling form submission and validation

Finally, let's handle form submission and validation. Update your views.py file with the following code:

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():
            # Process the data in form.cleaned_data as required
            # ...
            return redirect('success')
    else:
        form = ContactForm()

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

In this example, we added a check for the request method. If it's a POST request, we create an instance of ContactForm with the submitted data. Then, we call the is_valid() method to validate the form data. If the form is valid, we can process the form data and redirect to a success page.

This tutorial covered the basics of the Django Form System, including creating, validating, and rendering forms. You can extend this functionality by adding custom form fields, validation rules, and widgets as needed.

  1. Django form class and instance usage:

    • Description: Understand the concept of Django form classes and instances, which allow you to define the structure and behavior of a form.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          name = forms.CharField()
          email = forms.EmailField()
      
  2. Django form handling and submission:

    • Description: Explore how Django handles form submissions in views and processes the submitted data.
    • 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 form data
          else:
              form = MyForm()
      
          return render(request, 'template.html', {'form': form})
      
  3. Django form widgets and customization:

    • Description: Customize the appearance and behavior of form fields using Django form widgets.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class MyForm(forms.Form):
          my_field = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter data'}))
      
  4. ModelForm in Django forms system:

    • Description: Use Django ModelForms to automatically generate forms based on Django models.
    • 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']
      
  5. Working with form instances in Django:

    • Description: Understand how to create and manipulate instances of Django forms in views and templates.
    • Code Example:
      # views.py in your app
      from django.shortcuts import render
      from .forms import MyForm
      
      def my_view(request):
          form_instance = MyForm(initial={'name': 'John'})
          return render(request, 'template.html', {'form_instance': form_instance})
      
  6. Django form templates and rendering:

    • Description: Render forms in Django templates and customize their appearance using template tags.
    • Code Example:
      <!-- template.html in your app's templates directory -->
      <form method="post" action="{% url 'submit_form' %}">
          {% csrf_token %}
          {{ form.as_p }}
          <button type="submit">Submit</button>
      </form>
      
  7. Handling file uploads with Django forms:

    • Description: Enable file uploads in Django forms and handle file data in views.
    • Code Example:
      # forms.py in your app
      from django import forms
      
      class FileUploadForm(forms.Form):
          file = forms.FileField()
      
  8. Django form instance creation and modification:

    • Description: Dynamically create and modify form instances in Django views based on specific conditions or user interactions.
    • Code Example:
      # views.py in your app
      from django.shortcuts import render
      from .forms import MyForm
      
      def my_view(request):
          if some_condition:
              form_instance = MyForm()
          else:
              form_instance = MyForm(initial={'name': 'John'})
      
          return render(request, 'template.html', {'form_instance': form_instance})