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

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

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

请帮助我使中间模板工作。 我想这样做,因为我不想输入相同的代码不止一次。

90472 次浏览

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