简体   繁体   中英

how to properly use {% include %} tag to render a template (like partials) in django?

I have a list of links on the left side that display my subcategories. What I want to happen is when a user clicks on a subcategory, it will render data/content to the right.

I'm using class based views, so my initial page is a ListView (subcategory_list.html) that displays all the Subcategory objects.

So each Subcategory object has a DetailView (subcategory_detail.html).

I want to display the DetailView template (on the same page) based on which Subcategory link was clicked.

If I'm understanding correctly, I will have to use {% include %} tag and some AJAX???

How would I stop the browser from going to the new URL??

Thanks!

views.py

class SubcategoryListView(ListView):
model = Subcategory
template_name = 'categories/subcategory_list.html'

class SubcategoryDetailView(DetailView):
model = Subcategory
template_name = 'categories/subcategory_detail.html'

def get_context_data(self, **kwargs):
    context = super(SubcategoryDetailView, self).get_context_data(**kwargs)
    context['tasks'] = Task.objects.filter(subcategory=self.object)
    context['contractors'] = ContractorProfile.objects.filter(subcategory=self.object)
    return context

subcategory_list.html

{% extends 'base.html' %}

{% block content %}
<div class="container">
    <div class="col-md-3">
        {% for subcategory in object_list %}
            <p><a href="{% url 'categories:subcategory' subcategory.id %}">{{ subcategory.title }}</a></p>

        {% endfor %}
    </div>
    <div class="col-md-9">
        {% include 'categories/subcategory_detail.html' %}
    </div>
</div>

{% endblock %}

subcategory_detail.html

{% extends 'base.html' %}

{% block content %}
<div class="container">
    <h3>Subcategory: {{ object.title }}</h3>

    {% if user.is_authenticated%}
        <div class="row">
            {% for task in tasks %}
            <div class="thumbnail col-md-3">
                <img src="#" class="img-circle" />
                <div class="caption">
                    <p>Title: {{ task.title }}</p>
                    <p>Description: {{ task.description }}</p>
                    <p>Special Instructions: {{ task.special_instructions }}</p>
                    <p>Posted by: {{ task.user.username }}</p>
                </div>
            </div>
            {% cycle '' '' '' '</div><div class="row">' %}
            {% endfor %}

    {% endif %}
    </div>

</div>
<div class="container">
    <h3>Contractors Available:</h3>
    <div class="row">
        {% for contractor in contractors %}
        <div class="thumbnail col-md-3">
            <img src="#" class="img-circle" />
            <div class="caption">
                <p>Name: {{ contractor.contractor.username }}</p>
                <p>Rating: {{ contractor.rating }}</p>
                {% if contractor.contractor.is_online == True %}
                    <span class="glyphicon glyphicon-fire"></span> <span>Online Now</span>
                {% endif %}
            </div>
        </div>
        {% cycle '' '' '' '</div><div class="row">' %}
        {% endfor %}
</div>



{% endblock %}

urls.py

urlpatterns = [
    url(r'^subcategories/$', views.SubcategoryListView.as_view(), name='subcategories'),
    url(r'^subcategories/(?P<pk>\d+)/$', views.SubcategoryDetailView.as_view(), name='subcategory'),
]

Everything which is not done by refreshing the page but requires server content, requires the use of JavaScript. In this case, you want to inject HTML content (given by Django) into your page.

I'm gonna use jQuery here.

First of all, you want to identify the div where the content needs to be injected (for JavaScript to be able to refer to it) and the div.

Also, remove the {% include %} tag (OR let the tag render what you want rendered when the user load the page).

(in subcategory_list.html (which should be renamed subcategory.html )):

<div class="container subcategory_list">
    <div class="col-md-3">
        {% for subcategory in object_list %}
            <p><a href="{% url 'categories:subcategory' subcategory.id %}">{{ subcategory.title }}</a></p>

        {% endfor %}
    </div>
    <div class="col-md-9" id="subcategory_detail">
        {% include 'categories/subcategory_detail.html' %}
    </div>
</div>

Then you need to tell the a href to not load the page but let an ajax call happen.

<script type="text/javascript">
    $(function() { // shortcut for onDocumentReady

        // When you click an "a" tag who is child of an item with class "subcategory_list"…
        $('.subcategory_list>a').click(function() {

            var href = $(this).attr('href');

            // Use this if you want to add a loading gif or something similar
            // $('#subcategory_detail').html(my_cool_loading_gif_html)

            $.get(href, {
                success: function(response) {
                    // If the ajax call is successful, take the response and inject in div with id "subcategory_detail"
                    $('#subcategory_detail').html(response)
                },
                error: function(response) {
                    // Handle ajax errors here
                }
            })
            return false;
        });

    });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM