我有这个代码(它没有给我预期的结果)
#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 %}
请帮助我使用中间模板。 我想这样做,因为我不想多次输入相同的代码。
答案 0 :(得分:171)
就像@Besnik建议的那样,它非常简单:
{% include "subject_file_upload.html" with form=form foo=bar %}
documentation for include
提到了这一点。它还提到您可以使用only
仅使用给定变量呈现模板,而不继承任何其他变量。
谢谢@Besnik