52

In Django admin I want to override and implement my own form for a model (e.g. Invoice model).

I want the invoice form to have auto-fill fields for customer name, product name and I also want to do custom validation (such as credit limit for a customer). How can I override the default form provided by Django admin and implement my own?

I am new to Django, I appreciate any pointers.

rrawat
  • 1,071
  • 1
  • 15
  • 29
18bytes
  • 5,951
  • 7
  • 42
  • 69

2 Answers2

66

You can override forms for django's built-in admin by setting form attribute of ModelAdmin to your own form class. See:

  1. https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form
  2. https://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin

It's also possible to override form template - have a look at https://docs.djangoproject.com/en/dev/ref/contrib/admin/#custom-template-options

If you're looking specifically for autocomplete I can recommend https://github.com/crucialfelix/django-ajax-selects

Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
fest
  • 1,545
  • 12
  • 17
  • Is it possible to override the way the form looks as well? With auto complete feature for selected fields. – 18bytes Apr 06 '12 at 09:53
  • If you're looking for admin auto complete, I did not use django-ajax-selects, but [django-autocomplete-light](http://django-autocomplete-light.readthedocs.io/en/master/) is definitely worth it :) – GabLeRoux Dec 15 '16 at 15:59
36

How to override a form in the django admin according to the docs:

from django import forms
from django.contrib import admin
from myapp.models import Person

class PersonForm(forms.ModelForm):

    class Meta:
        model = Person
        exclude = ['name']

class PersonAdmin(admin.ModelAdmin):
    exclude = ['age']
    form = PersonForm
dan-klasson
  • 13,734
  • 14
  • 63
  • 101