Add custom form fields that are not part of the model

DjangoDjango Admin

Django Problem Overview


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

How can I do this?

I'm 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 they click 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 to be part of the model and DB, only the final expression.

Django Solutions


Solution 1 - Django

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.

Solution 2 - Django

It it possible to do in the admin, but there is not a very straightforward way to it. Also, I would like to advice to keep most business logic in your models, so you won't be dependent on the Django Admin.

Maybe it would be easier (and maybe even better) if you have the two seperate fields on your model. Then add a method on your model that combines them.

For example:

class MyModel(models.model):

    field1 = models.CharField(max_length=10)
    field2 = models.CharField(max_length=10)

    def combined_fields(self):
        return '{} {}'.format(self.field1, self.field2)

Then in the admin you can add the combined_fields() as a readonly field:

class MyModelAdmin(models.ModelAdmin):

    list_display = ('field1', 'field2', 'combined_fields')
    readonly_fields = ('combined_fields',)

    def combined_fields(self, obj):
        return obj.combined_fields()

If you want to store the combined_fields in the database you could also save it when you save the model:

def save(self, *args, **kwargs):
    self.field3 = self.combined_fields()
    super(MyModel, self).save(*args, **kwargs)

Solution 3 - Django

Django 2.1.1 The primary answer got me halfway to answering my question. It did not help me save the result to a field in my actual model. In my case I wanted a textfield that a user could enter data into, then when a save occurred the data would be processed and the result put into a field in the model and saved. While the original answer showed how to get the value from the extra field, it did not show how to save it back to the model at least in Django 2.1.1

This takes the value from an unbound custom field, processes, and saves it into my real description field:

class WidgetForm(forms.ModelForm):
    extra_field = forms.CharField(required=False)
    
    def processData(self, input):
        # example of error handling
        if False:
            raise forms.ValidationError('Processing failed!')

        return input + " has been processed"

    def save(self, commit=True):
        extra_field = self.cleaned_data.get('extra_field', None)

        # self.description = "my result" note that this does not work

        # Get the form instance so I can write to its fields
        instance = super(WidgetForm, self).save(commit=commit)
        
        # this writes the processed data to the description field
        instance.description = self.processData(extra_field)

        if commit:
            instance.save()

        return instance

    class Meta:
        model = Widget
        fields = "__all__"

Solution 4 - Django

You can always create new admin template, and do what you need in your admin_view (override the admin add URL to your admin_view):

url(r'^admin/mymodel/mymodel/add/$','admin_views.add_my_special_model')

Solution 5 - Django

If you absolutely only want to store the combined field on the model and not the two seperate fields, you could do something like this:

I never done something like this so I'm not completely sure how it will work out.

Solution 6 - Django

You might get help from my answer at : my response previous on multicheckchoice custom field

You can also extend multiple forms having different custom fields and then assigning them to your inlines class like stackedinline or tabularinline:

form =

This way you can avoid formset complication where you need to add multiple custom fields from multiple models.

so your modeladmin looks like:

inlines = [form1inline, form2inline,...]

In my previous response to the link here, you will find init and save methods.

init will load when you view the page and save will send it to database.

in these two methods you can do your logic to add strings and then save thereafter view it back in Django admin change_form or change_list depending where you want. list_display will show your fields on change_list. Let me know if it helps ... ....

class CohortDetailInline3(admin.StackedInline):
    model = CohortDetails
    form =  DisabilityTypesForm
...

class CohortDetailInline2(admin.StackedInline):
    model = CohortDetails
    form =  StudentRPLForm

... ...

@admin.register(Cohort)
class CohortAdmin(admin.ModelAdmin):         
        form = CityInlineForm
        inlines = [uploadInline,   cohortDetailInline1,
        CohortDetailInline2, CohortDetailInline3]
    
        list_select_related = True
    
        list_display = ['rto_student_code', 'first_name', 'family_name',]

...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmichalv82View Question on Stackoverflow
Solution 1 - DjangoVishnuView Answer on Stackoverflow
Solution 2 - DjangogitaarikView Answer on Stackoverflow
Solution 3 - DjangoMangoLassiView Answer on Stackoverflow
Solution 4 - DjangoEyal ChView Answer on Stackoverflow
Solution 5 - DjangogitaarikView Answer on Stackoverflow
Solution 6 - DjangoG-2View Answer on Stackoverflow