Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

html - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...