Reputation: 8608
I want to pass the previous URL in a context variable for a generic view:
class PostDeleteView(DeleteView, LoginRequiredMixin):
previous_url = self.request.META.get('HTTP_REFERER')
...
However, I can't access either self
or request
. How do I go about this?
Upvotes: 0
Views: 540
Reputation: 234
For example, if you wanted to use the tag {{ previous_url }}
in your templates you would override the get_context_data()
method.
Normally you could also pass extra context using the top level attribute extra_context
but the request object isn't available yet so you will be forced to override.
class PostDeleteView(LoginRequiredMixin, DeleteView):
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['previous_url'] = self.request.META.get('HTTP_REFERER')
return context
There's a site called classy class based views that breaks down all the methods used in Django's built in class based views so you can get an idea of how everything is put together behind the scenes.
Actually I just remembered an easier solution, if you have the request context processor enabled in TEMPLATES
in your project settings then you can access {{ request }}
directly in your templates.
'context_processors': [
...
'django.template.context_processors.request',
...
]
Upvotes: 3