112

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>

child template:

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

and my view

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

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

BUT,

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.

Vor
  • 33,215
  • 43
  • 135
  • 193

1 Answers1

283

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

Flimm
  • 136,138
  • 45
  • 251
  • 267
Vor
  • 33,215
  • 43
  • 135
  • 193
  • 4
    For completeness note that if you want to render the template only with the given variables (and doesn't inherit the parent context) you can add the "only" option: {% include "path/to/template.html" with form=form only }} – gonz Apr 01 '15 at 15:07
  • 9
    For completeness again, here is the link to "with": https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#include – Timo Apr 12 '15 at 07:36
  • @Vor If my view returns `context["these_items"]` and `context["other_items"]`, can I use include with this to substitute `{% for item in these_items %}` with `{% for item in other_items %}` ? – IordanouGiannis Feb 26 '18 at 11:14
  • 1
    for some reason, if the variable has an _ in its name, it doesn't work. Example: {% include "subject_file_upload.html" with my_form=form foo=bar %} . Any explanation for this? – Alan Tygel Sep 28 '19 at 21:53