在{%include%}标签Django中为子模板分配变量 [英] Assign variables to child template in {% include %} tag Django

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

问题描述

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

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>

子模板:

#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,但是表单不会更新数据库。

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

但是,

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

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.

推荐答案

喜欢@Besnik建议,这很简单:

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.

谢谢@Besnik

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

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