Reputation: 46919
In the following code i am trying to print display_name
in the template. But i see that it is empty .What am i doing wrong here ?
Views.py
class HomeView(TemplateView):
def get(self, request, *args, **kwargs):
display_name = "Test123"
return HttpResponseRedirect(reverse_lazy('site:index'),{'display_name': display_name})
In template
{{display_name}} //Its empty
Upvotes: 1
Views: 2169
Reputation: 6005
It's because you are re-directing. While you are adding display_name
to the context for this request, firing HttpResponseRedirect
means you are making a new request which isn't aware of the context you have created. Instead, you should add display_name
to the view you are redirecting to. possibly using a session variable if you need to pass the display_name
to the next page.
Edit: in response to your question
You should add display_name
to the session (all code is untested):
class HomeView(TemplateView):
def get(self, request, *args, **kwargs):
self.request.session['display_name'] = 'Test123'
self.request.session.save()
return HttpResponseRedirect(reverse_lazy('site:index'))
Then in the target page you'd use the get_content_data
method described by cor:
class MyView(TemplateView):
def get_context_data(self, **kwargs):
context = super(MyView, self).get_context_data(**kwargs)
if 'display_name' in self.request.session:
context['display_name'] = self.request.session['display_name']
del(self.request.session['display_name'])
return context
Upvotes: 1
Reputation: 3393
Do it like this:
class HomeView(TemplateView):
template_name = "yourtemplate.html"
def get_context_data(self, **kwargs):
context = super(HomeView, self).get_context_data(**kwargs)
context["display_name"] = "Test123"
return context
Upvotes: 0