简体   繁体   English

Django:从模板调用视图

[英]Django : Call a view from a template

How to call a view in my layout (template) ? 如何在我的布局(模板)中调用视图?

For example : I've a form on every pages of my website. 例如:我在网站的每个页面上都有一个表格。 I need to generate CSRF token for each pages but I don't want to put the generation code on every view. 我需要为每个页面生成CSRF令牌,但是我不想将生成代码放在每个视图上。

Thank you. 谢谢。

In Django, once you reach the template, I don't believe you can call something to the effect of Zend's Action Helper. 在Django中,一旦您到达模板,就无法相信您可以调用Zend的Action Helper。 Obviously, you could do an AJAX call to an exposed url in Django and retrieve the necessary data. 显然,您可以对Django中公开的网址执行AJAX调用,并检索必要的数据。 In that case you can provide the csrf token to the ajax calls as follows.. 在这种情况下,您可以按如下方式将csrf令牌提供给ajax调用。

$.ajaxSetup({data: {csrfmiddlewaretoken: '{{ csrf_token }}' },});

I'm not a hundred percent sure but you can implement something like Zend's Action Helper in a decorator (which could be applied to multiple views of your choice before processing the request) or in a context processor (which is applied to all views' processed request). 我不是百分百确定的,但是您可以在装饰器 (可以在处理请求之前将其应用于您选择的多个视图)或在上下文处理器 (应用于已处理的所有视图)中实现类似Zend的动作帮助器之类的功能请求)。

If your form is just HTML, then simply have a template containing the HTML and include that from other templates (or have it in your base template). 如果您的表单只是HTML,则只需有一个包含HTML的模板,然后将其包含在其他模板中(或将其包含在您的基本模板中)。 To generate a CSRF token, you simply use {% csrf_token %} in the template, as explained at https://docs.djangoproject.com/en/dev/ref/contrib/csrf/ 要生成CSRF令牌,只需在模板中使用{%csrf_token%},如https://docs.djangoproject.com/en/dev/ref/contrib/csrf/中所述

If you want to generate the HTML of a Django form, then you could add a context processor - explained at https://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext - that generates the form and then that will be available to all templates. 如果要生成Django表单的HTML,则可以添加上下文处理器-在https://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext中进行了说明生成表单,然后该表单将可用于所有模板。

def form_processor(request):
    form = Form()
    return { 'form': form.as_p() }

Template: 模板:

<form>{% csrf_token %}{{ {{ form }}</form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM