在{%include%}标记Django中为子模板分配变量


89

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

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

子模板:

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

和我的看法

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

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

但,

如果我跳过中间模板并直接转到上传表单,则可以正常工作:

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

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


13
您是否尝试过使用includewith with
贝斯尼克

Answers:


215

就像@Besnik建议的那样,它非常简单:

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

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

谢谢@Besnik


4
为了完整起见,请注意,如果您只想使用给定的变量来呈现模板(并且不继承父上下文),则可以添加“ only”选项:{%include form =“ path / to / template.html”仅限形式}}
gonz 2015年

8
为了完整起见
Timo

@Vor如果我的看法回报context["these_items"]context["other_items"],我可以使用包括与此代替{% for item in these_items %}{% for item in other_items %}
GiannisIordanou

由于某种原因,如果变量名中带有_,则该变量不起作用。示例:{%包括my_form = form foo = bar%}的“ subject_file_upload.html”。有什么解释吗?
艾伦·泰格尔
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.