Define a custom form for use in Django ModelAdmin Add View

I am trying to open a Django model in admin using the ModelAdmin class. ModelAdmin seems to suggest that you use the same form to add and change. I would like add_view to use a simplified form that lists only a few required fields. After submitting, it redirects to change_view and uses the default ModelForm form to display almost all fields.

What is the easiest way to do this? I checked the code, but I do not see a clear path. ModelAdmin tends to refer to a single self.form link in both add_view and change_view. I am thinking of overriding add_view (), but I don't want to redefine all the code. It might be more efficient to override get_form (), but I don't see how to determine if get_form () is called during add_view or change_view.

+3
source share
1 answer

get_form()parameter is passed objwhen called during change_view. Just find that if necessary, return the new form / settings parameters.

For instance:


class MyModelAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        # hide every other field apart from url
        # if we are adding
        if obj is None:
            kwargs['fields'] = ['url']
        return super(MyModelAdmin, self).get_form(request, obj, **kwargs)

Causes the form to display only the "url" field when adding and everything else otherwise.

+7
source

Source: https://habr.com/ru/post/1785241/


All Articles