📜 ⬆️ ⬇️

Scramble with tags # 3

A question in a comment to a previous post about tags moved me to write this note. I think it will be interesting not only to the questioner.
Thanks for the tags, but immediately the question is brewing - how can we get the tags? yes even teach what would choose objects with the requested tags


It is easy to add tag handling in URLs, for example, you can use URLs like "/ tag / TITLE_NAME /"


Then in the file of urls.py Django application you will need to register a handler pattern:
  urlpatterns = patterns ('',
 ...
 (r '^ tag / (? P <tag_id> \ w +) / $', 'myapp.views.items_list'),
 ...

')
It is meant that the request to the urla will be processed by the view (procedure in the MVC architecture) items_list
# ------------------------------------------------- -----------------------------
def items_list (request, tag_id = None):
“List of items. Filter items with pagination and tag_id provided - also filter items by tag »
initial = {} #initial filters for search form
num_per_page = 10
page = int (request.GET.get ('page', '1'))
if tag_id:
items = TaggedItem.objects.get_intersection_by_model (Item, (tag_id,))
else:
items = Item.objects.all ()
# paginate it
paginator = ObjectPaginator (items, num_per_page)
try:
items = paginator.get_page (page-1)
except InvalidPage:
page = 1
items = paginator.get_page (page-1)
content = {
"Items": items,
"Paginator": paginator,
"Current_page": page,
"Pages": range (1, paginator.pages + 1),
"Tag_id": tag_id,
}
return render_to_response ("items_list.html", content, context_instance = RequestContext (request))


That's all. In the above example, the procedure also processes the output of the entire list of items, plus a padjin is also done (pagination).

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


All Articles