Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override a form in Django admin

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.

like image 832
18bytes Avatar asked Apr 06 '12 07:04

18bytes


People also ask

What is admin ModelAdmin in Django?

One of the most powerful parts of Django is the automatic admin interface. It reads metadata from your models to provide a quick, model-centric interface where trusted users can manage content on your site. The admin's recommended use is limited to an organization's internal management tool.

What is form Is_valid () in Django?

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.

How can I remove extra's from Django admin panel?

Take a look at the Model Meta in the django documentation. Within a Model you can add class Meta this allows additional options for your model which handles things like singular and plural naming. Show activity on this post. inside model.py or inside your customized model file add class meta within a Model Class.


2 Answers

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

like image 121
fest Avatar answered Sep 20 '22 07:09

fest


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 
like image 25
dan-klasson Avatar answered Sep 20 '22 07:09

dan-klasson