Build a two-stage Django admin form for adding an

2019-03-31 12:58发布

问题:

Is it possible to build a two-stage form for creating an object in Django admin?

When an admin user visits /admin/my-app/article/add/, I'd like to display some options. Then, the app would display the creation page with pre-calculated fields based on the selections made.

回答1:

You could overwrite the add_view method on the ModelAdmin (Source) of myapp.article. It is responsible for rendering the modelform and adding objects to the database.

While adding your functionality, you likely want to keep the original code intact instead of copying/modifying it.

Draft

def add_view(self, request, **kwargs):
    if Stage1:
        do_my_stuff()
        return response
    else:
        return super(ModelAdmin, self).add_view(self, request, **kwargs)

Now you need to distinguish between the two stages. A parameter in the GET query string could do that. To pass initial data to a form in the admin, you only need to include the fieldname value pairs as parameters in the querystring.

Draft 2

def add_view(self, request, **kwargs):
    if 'stage2' not in request.GET:
        if request.method == 'POST':
            # calculate values
            parameters = 'field1=foo&field2=bar'
            return redirect('myapp_article_add' + '?stage2=1&' + parameters)
        else:
            # prepare form for selections
            return response
    else:
        return super(ModelAdmin, self).add_view(self, request, **kwargs)

You probably need to look at the code to return a correct response in your first stage. There are a couple of template variables add_view sets, but hopefully this is a good start to look further.