What are some useful non-embedded Django tags?

I am relatively new to Django, and I am trying to create my own toolkit for future projects. In my last project, when the built-in template tag did not do what I needed, I would turn the garbled mess into a template into a nightstand in this function. I will later find a template tag that would save me time and ugly code.

So what are some useful template tags that are not built into Django?

+3
source share
4 answers

I will begin.

http://www.djangosnippets.org/snippets/1350/

Intelligent {% if%} template tag

- , True, . , , .

{% block list-products %}
    {% if products|length > 12 %}
        <!-- Code for pagination -->
    {% endif %}

    <!-- Code for displaying 12 products on the page -->

{% endblock %}
+4

smart-if. if x > y , .

if Django 1.2 (. ), 9 2010 ..

+3

get_latest

jpartogi

class GetItemsNode(Node):
    def __init__(self, model, num, by, varname):
        self.num, self.varname = num, varname
        self.model = get_model(*model.split('.'))
        self.by = by

    def render(self, context):
        if hasattr(self.model, 'publicmgr') and not context['user'].is_authenticated():
            context[self.varname] = self.model.publicmgr.all().order_by(self.by)[:self.num]
        else:
            context[self.varname] = self.model._default_manager.all().order_by(self.by)[:self.num]
        return  ''

<div id="news_portlet" class="portlet">
{% get_sorted_items cms.news 5 by -created_on as items %}
{% include 'snippets/dl.html' %}
</div>
<div id="event_portlet" class="portlet">
{% get_sorted_items cms.event 5 by date as items %}
{% include 'snippets/dl.html' %}
</div>

get_sorted_items,

+1

{% autopaginate queryset%} (http://code.google.com/p/django-pagination/). :

#views.py
    obj_list = News.objects.filter(status=News.PUBLISHED)
    # do not use len(obj_list) - it evaluate QuerySet
    obj_count = obj_list.count()

#news_index.html
    {% load pagination_tags %}
    ...
    # do not use {% if obj_list %}
    {% if obj_count %}
        <div class="news">
        <ul>
        {% autopaginate obj_list 10 %}
        {% for item in obj_list %}
            <li><a href="...">{{ item.title }}</a></li>
        {% endfor %}
        </ul>
        </div>
        {% paginate %}
    {% else %}
        Empty list
    {% endif %}

, obj_list - http://docs.djangoproject.com/en/dev/ref/models/querysets/#id1

+1

Source: https://habr.com/ru/post/1719519/


All Articles