django admin custom form usage

django admin custom form usage

Django admin allows us to use custom form. In most of the cases we use default admin provided by django. But, in some cases we may need to use some validations on the model fields or we may want to skip some fields and update these fields while saving it. In this kinds of situations we can solve it by using the custom form in django admin.

implementation of django admin custom form

models.py

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)
    title = models.CharField(max_length=3)
    birth_date = models.DateField(blank=True, null=True)

    def __str__(self):
        return '{}'.format(self.name)

forms.py

from django import forms
from .models import Author

class AuthorForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        print("My custom admin Form")
        super().__init__(*args, **kwargs)

    class Meta:
        fields = ('name', 'title', 'birth_date')

admin.py

from django.contrib import admin
from .models import Author
from .forms import AuthorForm

class AuthorAdmin(admin.ModelAdmin):
    form = AuthorForm

admin.site.register(Author, AuthorAdmin)

In above code we have registered the model "Author" in the admin with another class "AuthorAdmin". when we register it with another class "AuthorAdmin" then the default behaviour of the model will be overridden by the configurations that we make in the class "AuthorAdmin". In above code we have used a custom form. So, when we register the model with the model admin class then it will use the the properties/settings that we defined init.

How can we confirm that our custom form is working ?

  • If you observe the terminal when you run the server and access the add/edit page in the admin then you will see the text "My custom admin Form".
  • So, it indicates that the custom form is being used by the django admin.

You can see the sample project in the github "https://github.com/AnjaneyuluBatta505/learnbatta/tree/master/django/django_admin_custom_form"