django admin - add custom form fields that are not part of the model

michalv82 picture michalv82 · Jul 30, 2013 · Viewed 100.3k times · Source

I have a model registered in the admin site. One of its fields is a long string expression. I'd like to add custom form fields to the add/update page of this model in the admin that based on these fields values I will build the long string expression and save it in the relevant model field.

How can I do that?

UPDATE: Basically what I'm doing is building a mathematical or string expression from symbols, the user chooses symbols (these are the custom fields that are not part of the model) and when he clicks save then I create a string expression representation from the list of symbols and store it in the DB. I don't want the symbols are part of the model and DB, only the final expression.

Answer

Vishnu picture Vishnu · Apr 28, 2014

Either in your admin.py or in a separate forms.py you can add a ModelForm class and then declare your extra fields inside that as you normally would. I've also given an example of how you might use these values in form.save():

from django import forms
from yourapp.models import YourModel


class YourModelForm(forms.ModelForm):

    extra_field = forms.CharField()

    def save(self, commit=True):
        extra_field = self.cleaned_data.get('extra_field', None)
        # ...do something with extra_field here...
        return super(YourModelForm, self).save(commit=commit)

    class Meta:
        model = YourModel

To have the extra fields appearing in the admin just:

  1. edit your admin.py and set the form property to refer to the form you created above
  2. include your new fields in your fields or fieldsets declaration

Like this:

class YourModelAdmin(admin.ModelAdmin):

    form = YourModelForm

    fieldsets = (
        (None, {
            'fields': ('name', 'description', 'extra_field',),
        }),
    )

UPDATE: In django 1.8 you need to add fields = '__all__' to the metaclass of YourModelForm.