Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign variables to child template in {% include %} tag 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> 

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.

like image 930
Vor Avatar asked Jul 24 '12 21:07

Vor


People also ask

What {% include %} does?

{% include %} Processes a partial template. Any variables in the parent template will be available in the partial template. Variables set from the partial template using the set or assign tags will be available in the parent template.

What {% include %} does in Django?

The include tag allows you include a template inside the current template. This is useful when you have a block of content that are the same for many pages.

Why is {% extends %} tag used?

The extends tag is used to declare a parent template. It should be the very first tag used in a child template and a child template can only extend up to one parent template. To summarize, parent templates define blocks and child templates will override the contents of those blocks.

When {% extends %} is used for inheriting a template?

extends tag is used for inheritance of templates in django. One needs to repeat the same code again and again. Using extends we can inherit templates as well as variables.


1 Answers

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

like image 171
Vor Avatar answered Sep 21 '22 16:09

Vor