Home > other >  How to add field in django admin non related to model?
How to add field in django admin non related to model?

Time:11-22

I want to add a checkbox in Django Admin that is not related to a field in my model. Depending on the value of the checkbox, I want to do some extra actions.

class DeviceAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        #if checkbox:
        #    do_extra_actions()
        super(DeviceAdmin, self).save_model(request, obj, form, change)

How to add this checkbox in the django admin form for my model Device and get the value in save_model function ?

CodePudding user response:

You can first create a ModelForm with such extra checkbox:

class DeviceModelForm(forms.ModelForm):
    extra_checkbox = forms.BooleanField(required=False)

Then you plug this into the DeviceAdmin and inspect its value:

class DeviceAdmin(admin.ModelAdmin):
    form = DeviceModelForm
    
    def save_model(self, request, obj, form, change):
        if form.cleaned_data['extra_checkbox']:
            # do_extra_actions()
            pass
        return super().save_model(request, obj, form, change)
  • Related