0
0
Djangoframework~5 mins

ModelForm for model-backed forms in Django

Choose your learning style9 modes available
Introduction

A ModelForm helps you create a form directly from a database model. It saves time by automatically making form fields that match your model fields.

When you want users to add or edit data stored in your database.
When you want to avoid writing form fields manually for each model field.
When you want to keep your form and model in sync easily.
When you want to validate user input based on your model rules.
When you want to quickly create admin or user input forms.
Syntax
Django
from django.forms import ModelForm
from .models import YourModel

class YourModelForm(ModelForm):
    class Meta:
        model = YourModel
        fields = ['field1', 'field2', 'field3']

The Meta class inside your form tells Django which model to use.

The fields list controls which model fields appear in the form.

Examples
This form will have fields for the title and author of a Book model.
Django
class BookForm(ModelForm):
    class Meta:
        model = Book
        fields = ['title', 'author']
This form will include all fields from the Author model.
Django
class AuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = '__all__'
This form will include all Product fields except created_at and updated_at.
Django
class ProductForm(ModelForm):
    class Meta:
        model = Product
        exclude = ['created_at', 'updated_at']
Sample Program

This example shows a Contact model with three fields. The ContactForm automatically creates form fields for these. In the view, the form is shown on GET requests and saved on valid POST requests.

Django
from django.db import models
from django.forms import ModelForm

# Define a simple model
class Contact(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()
    message = models.TextField()

# Create a ModelForm for Contact
class ContactForm(ModelForm):
    class Meta:
        model = Contact
        fields = ['name', 'email', 'message']

# Example usage in a Django view (simplified)
from django.http import HttpResponse
from django.shortcuts import render

def contact_view(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            form.save()  # Saves data to the database
            return HttpResponse('Thank you for your message!')
    else:
        form = ContactForm()
    return render(request, 'contact.html', {'form': form})
OutputSuccess
Important Notes

Always specify which fields to include or exclude to avoid security risks.

ModelForm automatically handles validation based on your model field types.

You can customize form fields by overriding them in your ModelForm class.

Summary

ModelForm creates forms from models automatically.

Use the Meta class to link the form to a model and choose fields.

It saves time and keeps forms consistent with your database.