1

How can we access the context passed in template in method views?

urls.py

urlpatterns = [
    path('', views.method_A, name='first_view'),
    path('method_B', views.method_B, name='second_view'),
]
def method_A(request):
    context = {"name":"sample"}
    html_template = loader.get_template('some_template.html')
    return HttpResponse(html_template.render(context, request))

Template as

<div>
   {{name}}
   <a href="method_B">Redirect</a>
</div>
def method_B(request):
    # Here how to get context which was present earlier
    context = {"second":"second"}
    html_template = loader.get_template('template_B.html')
    return HttpResponse(html_template.render(context, request))

How we can get context in method based views in django.? So that it can be used in another templates.

John Byro
  • 674
  • 3
  • 13
  • Please show your **urls.py**. Also do you want to pass information between views or just re-used the same context variables in both views? – Lewis Dec 06 '21 at 09:40
  • @Lewis, basically , I need to access the previous information of template (previous context) so that i can update the context to render in another context. Passing information between views would be good here. – John Byro Dec 06 '21 at 09:45
  • No, you can’t access the context from a previous view. You’ll need to store the data in some way e.g. in the query string `Redirect` or in a cookie. – Alasdair Dec 06 '21 at 09:49
  • @Alasdair, passing entire context in query string and then parsing it wont be an efficient way. Can we store context at one place so that it can be accessed. – John Byro Dec 06 '21 at 10:02
  • The querystring was just an example. You could store it in a cookie as I suggested, or the database, or a cache. It’s up to you how you implement it. – Alasdair Dec 06 '21 at 11:28

1 Answers1

2

You can store as a session variable.

Views

def method_A(request):
    html_template = loader.get_template('some_template.html')
    request.session['my_context'] = 'Example' #Setting Cookie
    return HttpResponse(html_template.render(context, request))

def method_B(request):
    # Here how to get context which was present earlier
    my_context = request.session.pop('my_context', None) # Getting Cookie
    html_template = loader.get_template('template_B.html')
    return HttpResponse(html_template.render(context, request))
Lewis
  • 2,718
  • 1
  • 11
  • 28