Build a two-stage Django admin form for adding an object?

后端 未结 1 822
小蘑菇
小蘑菇 2021-02-10 16:59

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

相关标签:
1条回答
  • 2021-02-10 17:16

    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.

    0 讨论(0)
提交回复
热议问题