1

我们如何在方法视图context中访问传入的模板?

网址.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))

模板为

<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))

我们如何在 django 中获取基于方法的视图中的上下文。?这样它就可以在另一个模板中使用。

4

1 回答 1

2

您可以存储为session变量。

意见

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))
于 2021-12-06T10:08:26.483 回答