Can I call a view from within another view?

前端 未结 4 1614
温柔的废话
温柔的废话 2020-11-29 00:29

One of my view needs to add an item, along with other functionality, but I already have another view which specifically adds an item.

Can I do something like:

4条回答
  •  温柔的废话
    2020-11-29 00:43

    A better way is to use the template system. Combining ideas from @Seth and @brady:

    def specific_add_item_view(request, extra_context_stuff=None):
        Item.objects.create()
        context_variables = {} # obviously want to populate this
        if extra_context_stuff:
            context_variables.update(extra_context_stuff)
        return render(request, 'app_name/view1_template.html', context_variables)
    
    def bigger_view(request):
        extra_context_stuff = {'big_view': True}
        return specific_add_item_view(request, extra_context_stuff)
    

    And your app_name/view1_template.html might contain a conditional template tag

    {% if big_view %}
    

    Extra html for the bigger view

    {% endif %}

提交回复
热议问题