Collect more information on the Django admin page?

on save, if the user selects a certain option, I want to take the user to a page where they can have another fillable field, and then redirect to the default admin page.

0


a source to share


1 answer


Instead of being redirected to a new page, you can simply override the form that the create and update pages use. This allows additional fields to be added to the model form while keeping all form processing in one place.

First, you need to configure your ModelAdmin to use your custom form:

admin.py

from django.contrib import admin
from forms import BookAdminForm
from models import Book

class BookAdmin(admin.ModelAdmin):
    form = BookAdminForm

admin.site.register(Book, BookAdmin)

      

forms.py



from django import forms

class BookAdminForm(forms.ModelForm):
    additional_field = forms.CharField(max_length=100)

    class Meta:
        model = Book

      

Next, you need to override the save method to check if a "specific option" is selected, and then handle the additional field accordingly. Inside your class, you need something like this:

def save(self, *args, **kwargs):
    if self.cleaned_data['certain_field'].value == 'certain option':
        # process additional_field
    # don't forget to call super to save the rest of the form
    super(BookAdminForm, self).save(*arg, **kwargs)

      

NOTE. This code is untested, but it should point you in the right direction.

It is also possible to override the methodsave_model()

in ModelAdmin.

0


a source







All Articles