如何正确使用{%include%}标签来渲染django中的模板(如部分)?

时间:2015-12-24 21:26:57

标签: python ajax django django-templates django-views

我在左侧有一个链接列表,显示我的子类别。我想要发生的是当用户点击子类别时,它将向右呈现数据/内容。

我正在使用基于类的视图,因此我的初始页面是一个ListView(subcategory_list.html),它显示所有子类别对象。

因此每个Subcategory对象都有一个DetailView(subcategory_detail.html)。

我想根据点击的子类别链接显示DetailView模板(在同一页面上)。

如果我理解正确,我将不得不使用{%include%}标签和一些AJAX ???

如何阻止浏览器转到新网址?

谢谢!

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'),
]

1 个答案:

答案 0 :(得分:0)

通过刷新页面但需要服务器内容而未完成的所有操作都需要使用JavaScript。在这种情况下,您希望将HTML内容(由Django提供)注入您的页面。

我将在这里使用jQuery。

首先,您要确定需要注入内容的div(以便JavaScript能够引用它)和div。

此外,删除{% include %}标记(或让标记呈现用户加载页面时要呈现的内容)。

(在subcategory_list.html中(应重命名为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>

然后你需要告诉a href不加载页面但是让ajax调用发生。

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