Search code examples
djangodjango-viewsdjango-class-based-views

Send context the template in a class based view


How can I send context to my template in a class-based view with the get_object function?

This is my class:

class DetailMessages(LoginRequiredMixin, DetailView, ChannelFormMixin):
    template_name = 'DM/chat.html'
    def get_object(self, *args, **kwargs):
        my_username = self.request.user.username
        username = self.kwargs.get("username")
        channel, _ = Channel.objects.get_dm_channel(my_username, username)
        if channel == None:
            raise Http404
        context = {"example1" : "I want this on the template", "example2" : "I want this on the template too"}
        return channel

Solution

  • It's usually not good idea to mix methods in class based views. You can pass context in two ways: in get() or get_context_data(). Examples:

    # or
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["example1"] = "I want this on the template"
        context["example2"] = "I want this on the template too"
        return context
    
    # or
    
    def get(self, request, *args, **kwargs):
        context = {}
        context["example1"] = "I want this on the template"
        context["example2"] = "I want this on the template too"
        return render(..., context=context)
    

    If you don't actually need to operate with get() (or post()) method, then much better way is to leave context managing to get_context_data() method.