Структура для передачи данных на страницу в представлении/шаблоне

Я пытаюсь создать приложение под названием «Сделки», которое создаст блок на моей домашней странице и отобразит кучу сделок. Это создано в Django/Mezzanine. Однако я не могу заставить данные словаря правильно распознаваться шаблоном. Может кто-нибудь объяснить, что я делаю неправильно:

В моем основном файле base.html у меня есть следующее:

<div class="col-md-9 middle">
    {% block deals %}
    {% ifinstalled deals %}
    {% include "deals.html" %}
    {% endifinstalled %}
    {% endblock %}
    {% block main %}{% endblock %}
</div>

В моей домашней папке у меня есть приложение под названием Deals. В этой папке есть подкаталог templates, который содержит файл deals.html. Этот файл вызывается правильно, потому что условие else, показанное ниже, отображается на странице.

Это мой файл Deals.html:

<div class="row">
        {% if deals %}
                {% for deals in deals %}
                        <div class="deal col-sm-6 col-md-4">
                                <div class="thumbnail">
                                        <a href="{{ deal.url }}" target="_blank"><img alt=" {{ deal.title }}" src="{{ deal.image }}" data-holder-rendered="true" style="height: 200px; width: 100%; display: block;"></a>
                                        <div class="caption">
                                                <h3 id="thumbnail-label"><a href="{{ deal.url }}" target="_blank">{{ deal.title }}</a><a class="anchorjs-link" href="#thumbnail-label"><span class="anchorjs-icon"></span></a></h3>
                                                <h4>{{ deal.price }}</h4>
                                                <p>{{ deal.description }}</p>
                                                <div class="row">
                                                        <div class="col-xs-6">
                                                                <a href="{{ deal.url }}" class="btn btn-primary" role="button" target="_blank">View</a>
                                                                <button type="button" class="favoritebutton btn btn-default btn-md" data-toggle="tooltip" data-placement="right" title="Click to save">
                                                                        <span class="glyphicon glyphicon-heart empty"></span>
                                                                </button>
                                                        </div>
                                                        <div class="col-xs-6">
                                                                <img class="providerlogo" src="{{ deal.provider_img }}" alt="{{ deal.provider }}"/>
                                                        </div>
                                                </div>
                                        </div>
                                </div>
                        </div>
                {% endfor %}
        {% else %}
                <strong>There are no current deals that match your selection. Try expanding your selection and get going!</strong>
        {% endif %}
</div>

В разделе Deals/views.py у меня есть следующее:

from django.shortcuts import render,render_to_response
from django.http import HttpResponse
from django.template import RequestContext

# Create your views here.
def deals(request,slug):
    """Handles the deals"""
    data = {'deals':[{'title':'5 Days 4 Nights in New York City',
                     'price':'$1799',
                     'description':'Check out the city that never sleeps. Go skating in Rockefeller Center or catch a show on Broadway. This is the trip of a lifetime.',
                     'provider_img':'http://static.example.com/20150502/partners/logo/small/xgroupon.png.pagespeed.ic.B-5dk6Jr_C.png',
                     'provider':'Name',
                     'url':'http://www.example.com/deal1',
                     'img':'http://media-cdn.tripadvisor.com/media/photo-s/03/9b/2d/f2/new-york-city.jpg'},
                     {'title':'Dream trip to the carribbean',
                     'price':'$2199',
                     'description':'Enjoy sun, sand and cocktails. This is a trip of a lifetime to sit back and relax. Forget your busy life and enjoy the carribbean',
                     'provider_img':'http://static.example.com/20150502/partners/logo/small/xgroupon.png.pagespeed.ic.B-5dk6Jr_C.png',
                     'provider':'Name',
                     'url':'http://www.example.com/deal2',
                     'img':'http://i.telegraph.co.uk/multimedia/archive/02464/caribbean_2464021b.jpg'},
                     {'title':'Airfare and Hotel to Paris',
                     'price':'$2400',
                     'description':'It\'s the city of love. Fabulous food, wine and romance in Paris. This trip includes hotel and airfare. Prices are for two or more people",
                     'provider_img':'http://static.example.com/20150502//partners/logo/small/xgroupon.png.pagespeed.ic.B-5dk6Jr_C.png',
                     'provider':'Name',
                     'url':'http://www.example.com/deal3',
                     'img':'http://cache.graphicslib.viator.com/graphicslib/thumbs674x446/2050/SITours/eiffel-tower-paris-moulin-rouge-show-and-seine-river-cruise-in-paris-150305.jpg'}
                     ]
            }
    return render_to_response('templates/deals.html',data,context_instance=RequestContext(request))

На данный момент рендерится следующее:

There are no current deals that match your selection. Try expanding your selection and get going!

Может ли кто-нибудь указать, что я делаю неправильно? Кажется, что словарь, отправляемый на страницу, не распознается.

EDIT Как и предполагалось, проблема связана с тегами шаблона. Я добавил следующее в верхнюю часть «deals.html»:

{% deals %}

и изменил мой views.py на:

from django.shortcuts import render,render_to_response
from django.http import HttpResponse
from django.template import RequestContext

# Create your views here.
@register.inclusion_tag('deals.html')
def deals():
    """Handles the deals"""
    data = {'deals':[{'title':'5 Days 4 Nights in New York City',
                     'price':'$1799',
                     'description':'Check out the city that never sleeps. Go skating in Rockefeller Center or catch a show on Broadway. This is the trip of a lifetime.',
                     'provider_img':'http://static.example.com/20150502/partners/logo/small/xgroupon.png.pagespeed.ic.B-5dk6Jr_C.png',
                     'provider':'Name',
                     'url':'http://www.example.com/deal1',
                     'img':'http://media-cdn.tripadvisor.com/media/photo-s/03/9b/2d/f2/new-york-city.jpg'},
                     {'title':'Dream trip to the carribbean',
                     'price':'$2199',
                     'description':'Enjoy sun, sand and cocktails. This is a trip of a lifetime to sit back and relax. Forget your busy life and enjoy the carribbean',
                     'provider_img':'http://static.example.com/20150502/partners/logo/small/xgroupon.png.pagespeed.ic.B-5dk6Jr_C.png',
                     'provider':'Name',
                     'url':'http://www.example.com/deal2',
                     'img':'http://i.telegraph.co.uk/multimedia/archive/02464/caribbean_2464021b.jpg'},
                     {'title':'Airfare and Hotel to Paris',
                     'price':'$2400',
                     'description':'It\'s the city of love. Fabulous food, wine and romance in Paris. This trip includes hotel and airfare. Prices are for two or more people",
                     'provider_img':'http://static.example.com/20150502//partners/logo/small/xgroupon.png.pagespeed.ic.B-5dk6Jr_C.png',
                     'provider':'Name',
                     'url':'http://www.example.com/deal3',
                     'img':'http://cache.graphicslib.viator.com/graphicslib/thumbs674x446/2050/SITours/eiffel-tower-paris-moulin-rouge-show-and-seine-river-cruise-in-paris-150305.jpg'}
                     ]
            }
    return data

Но теперь я получаю следующую ошибку, предполагающую, что она не регистрируется правильно:

Request Method: GET
Request URL:    http://localhost:8000/
Django Version: 1.6.11
Exception Type: TemplateSyntaxError
Exception Value:    
Invalid block tag: 'deals'

person user2694306    schedule 21.05.2015    source источник


Ответы (1)


Кажется, вы предполагаете, что представление deal.deals() вызывается автоматически, когда вы куда-то включаете свой шаблон deals.html. Это работает иначе — в Django «представления» на самом деле являются обработчиками запросов, кодом iow, который вызывается с HTTP-запросом и возвращает HTTP-ответ.

Решением вашей проблемы является пользовательский тег шаблона - в данном случае inclusion_tag (как задокументировано здесь). Хорошие новости: у вас уже есть большая часть кода, поэтому ваша проблема должна быть решена через несколько минут.

person bruno desthuilliers    schedule 21.05.2015
comment
Я обновил свой вопрос, чтобы отразить дополнительную проблему. - person user2694306; 21.05.2015
comment
Вы не прочитали всю документацию о тегах шаблонов, не так ли? Теги вашего шаблона не должны находиться в yourapp/views.py, см. docs.djangoproject.com/en/1.8/howto/custom-template-tags/ - person bruno desthuilliers; 21.05.2015
comment
Извините, но я не понимаю. Что будет в view.py, а что в polls_extra.py? Знаете ли вы какие-нибудь рабочие примеры, объясняющие это? - person user2694306; 21.05.2015
comment
В polls_extra.py ничего не попадает. Откуда вы взяли, что вам нужен файл polls_extra.py? Как уже говорилось, на самом деле это является примером. Общий падеж прописан целыми буквами в приведенных выше абзацах. Если вы этого не понимаете, начните с официального руководства по Python (чтобы вы хотя бы поняли, что означает пакет и модуль). - person bruno desthuilliers; 21.05.2015