将变量分配给 {% include %} 标记 Django 中的子模板 [英] Assign variables to child template in {% include %} tag Django

查看:23
本文介绍了将变量分配给 {% include %} 标记 Django 中的子模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码(它没有给我预期的结果)

#subject_content.html{% 块主菜单 %}{% 包括subject_base.html"%}{% 结束块 %}#subject_base.html........<div id="homework" class="tab-section"><h2>家庭作业</h2>{% 包括subject_file_upload.html"%}

子模板:

#subject_file_upload.html<form action="."method="post" enctype="multipart/form-data">{% csrf_token %}{{ form.as_p }}<输入类型=提交"值=提交"></表单>

我的观点

#views.py@需要登录定义主题(请求,用户名,主题):如果 request.method == "POST":form = CarsForm(request.POST, request.FILES)如果 form.is_valid():表单.save()返回 HttpResponseRedirect("/")表单 = CarsForm()return render_to_response('subject_content.html', {'form':form}, context_instance=RequestContext(request))

上面的代码按照我想要的方式创建 HTML,但是表单不会更新数据库.

但是,

如果我跳过中间模板直接进入上传表单,它工作正常:

#subject_content.html{% 块主菜单 %}{% 包括subject_file_upload.html"%}{% 结束块 %}

请帮助我使其与中间模板一起使用.我想这样做,因为我不想多次输入相同的代码.

解决方案

就像@Besnik 建议的那样,这很简单:

{% 包含subject_file_upload.html"和 form=form foo=bar %}

include 的文档提到了这一点.它还提到您可以使用 only 仅使用给定的变量呈现模板,而无需继承任何其他变量.

谢谢@Besnik

I have this code(which doesn't give me expected result)

#subject_content.html
{% block main-menu %}
    {% include "subject_base.html" %}
{% endblock %}


#subject_base.html
....
....
    <div id="homework" class="tab-section">
        <h2>Homework</h2>
            {% include "subject_file_upload.html" %}
    </div>

child template:

#subject_file_upload.html
    <form action="." method="post" enctype="multipart/form-data">{% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="submit">
    </form>

and my view

#views.py
@login_required
def subject(request,username, subject):
    if request.method == "POST":
        form = CarsForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/")
    form = CarsForm()
    return render_to_response('subject_content.html', {'form':form}, context_instance=RequestContext(request))

The above code creates HTML in the way I want it to be, however the form does not update database.

BUT,

If I skip the middle template and go directly to the uploading form, it works fine:

#subject_content.html
{% block main-menu %}
    {% include "subject_file_upload.html" %}
{% endblock %}

Help me please to make it work with middle template. I want to do this, because I don't wan't to type the same code more than once.

解决方案

Like @Besnik suggested, it's pretty simple:

{% include "subject_file_upload.html" with form=form foo=bar %}

The documentation for include mentions this. It also mentions that you can use only to render the template with the given variables only, without inheriting any other variables.

Thank you @Besnik

这篇关于将变量分配给 {% include %} 标记 Django 中的子模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆