2012-07-24 80 views
50

我有這樣的代碼(不給我預期的結果)分配變量子模板中{%包含%}標籤的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 %} 

請幫助我,使之與中間模板的工作。 我想這樣做,因爲我不想多次輸入相同的代碼。

+12

你是否嘗試過用'with'使用'include'? – Besnik 2012-07-24 21:25:22

+0

@Besnik謝謝!!!!有用!!! – Vor 2012-07-24 21:34:37

回答

127

像@Besnik建議,這是很簡單的:

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

documentation for include提到了這一點。它還提到您可以使用only僅使用給定變量呈現模板,而不會繼承任何其他變量。

謝謝你@Besnik

+3

爲了完整性,請注意,如果您只想使用給定變量渲染模板(並且不繼承父上下文),則可以添加「僅」選項:{%include「path/to/template.html」with form = form only}} – gonz 2015-04-01 15:07:33

+8

爲了完整起見,這裏是「with」的鏈接:https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#include – Timo 2015-04-12 07:36:39

+0

歷史記錄:https:// code .djangoproject.com/ticket/7817 – Paolo 2015-11-05 17:18:41