Home > Blockchain >  How to provide context to django class view get method
How to provide context to django class view get method

Time:10-20

I have a class based view which I want supply some context to but I don't know how I can achieve this Below is the views.py

class Dashboard(LoginRequiredMixin, View):
    def get(self, request):

        if request.user is not None and len(request.user.payment_set.all()):
            if request.user.is_active and request.user.payment_set.first().active:
                print(eligible_to_review(self.request))
                return render(request, 'main.html')
            else:
                return redirect('home')
        else:
            return redirect('membership')

How can I pass a context to this view in order to use it in the html file

CodePudding user response:

I think the cleanest way is to replace the inheritance from View with TemplateView - you can provide a get_context_data method to do whatever extra context stuff you need.

Ideally you'd not need to provide a get() but since you've got some extra logic there with redirects you probably need that there. I would guess that you probably want the eligible_to_review() to be in the get_context_data since it's not clear why you would be printing it (to what terminal?). Also given the use of LoginRequiredMixin you can be confident that when you get to the get() the request.user is both set and active - so those parts of the tests are reducndant.


class Dashboard(LoginRequiredMixin, TemplateView):

    template_name="main.html"

    def get_context_data(self, **kwargs):
        context=super().get_context_data(**kwargs)
        context["whatever"]="Some stuff" # This is where you add extra context you need.
        return context

    def def get(self, request, *args, **kwargs):

        if len(request.user.payment_set.all()): #request.user is definitely set here!
            if request.user.payment_set.first().active: #request.user is also active!
                print(eligible_to_review(self.request))
                return super().def get(request, *args, **kwargs)
            else:
                return redirect('home')
        else:
            return redirect('membership')
  • Related