[Django]-Passing context variable in generic.UpdateView

7👍

You can patch the get_context_data [Django-doc]:

from django.views.generic.detail import UpdateView

class MyUpdateView(UpdateView):

    model = MyModel

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        if somecondition:
            load_template = 'damage/menus/menu.html'
        else:
            load_template = 'damage/menus/sidebarmenu.html'
        context['load_template'] = load_template
        return context

This will thus add a variable named load_template to the context. Note that user is not defined here. The user that is logged in, is the self.request.user. For example:

from django.views.generic.detail import UpdateView

class MyUpdateView(UpdateView):

    model = MyModel

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        if not request.user.is_authenticated:
            load_template = 'damage/menus/menu.html'
        else:
            load_template = 'damage/menus/sidebarmenu.html'
        context['load_template'] = load_template
        return context

Leave a comment