A2oz

How Do You Display a Model Form in a Django Template?

Published in Django 2 mins read

You can display a Django model form in a template using the {{ form }} template tag. This tag renders the form's HTML structure, including labels, input fields, and submit buttons.

Steps to Display a Model Form in a Django Template:

  1. Create a Django form: Use the ModelForm class to create a form that represents your model.

  2. Pass the form to the template: In your view, create an instance of the form and pass it to the template context.

  3. Render the form in the template: Use the {{ form }} template tag to render the form in your template.

Example:

models.py:

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=200)
    price = models.DecimalField(max_digits=6, decimal_places=2)

forms.py:

from django import forms
from .models import Product

class ProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = '__all__'

views.py:

from django.shortcuts import render
from .forms import ProductForm

def product_create(request):
    if request.method == 'POST':
        form = ProductForm(request.POST)
        if form.is_valid():
            form.save()
            # Redirect to a success page or other appropriate action
    else:
        form = ProductForm()
    return render(request, 'product_form.html', {'form': form})

product_form.html:

<h1>Create a New Product</h1>
<form method="post">
    {% csrf_token %}
    {{ form }}
    <button type="submit">Save</button>
</form>

This example creates a form for the Product model, renders it in a template, and handles form submission.

Additional Tips:

  • You can customize the form's appearance using CSS.
  • The {{ form }} tag automatically generates the necessary input fields, labels, and validation messages.
  • Use the {{ form.errors }} template tag to display any validation errors.

Related Articles