Monday, 12 July 2021

*Episode 17* PYTHON ( Creating a Tags Page of Django)



Creating a tags page


This episode covers :-


 1) How to create a “tags” page to display tagged items.

 2) How to do lookups across relationships.

 3) How to re-use templates.


  •  Setup :-

Terminal

cp -fr 18-Tags-ManyToMany 19-Tags-Page

cd 19-Tags-Page

source ../venv/bin/activate


  •  Adding tags path :-

     Edit mysite urls.py file and add a path to the tags page:

mysite/urls.py

urlpatterns = [

path('admin/', admin.site.urls),

path('', myapp_views.index, name='index'),

path('tags/<slug:slug>/', myapp_views.tags, name='tags'\

), # < here

]


  •  Adding the slug field :-

     Edit myapp models.py file and add a SlugField to the Tag model:

myapp/models.py

from django.db import models

from django.utils.text import slugify # < here

class Tag(models.Model):

title = models.CharField(max_length=255, default='')

slug = models.SlugField(blank=True, default='') # < here

def __str__(self):

return self.title

def save(self, *args, **kwargs): # < here

self.slug = slugify(self.title)

super(Tag, self).save()


  •  Creating the tags view :-

     Edit myapp views.py file and add a tags view function:

myapp/views.py

from django.shortcuts import render

from myapp.models import Flower

def index(request):

flowers = Flower.objects.all()

return render(request, 'myapp/index.html', {'flowers': \

flowers })

def tags(request, slug=None): # < here

flowers = Flower.objects.filter(tags__slug=slug)

return render(request, 'myapp/index.html', {'flowers': \

flowers })


     Run migrations:

Terminal

python manage.py makemigrations

python manage.py migrate


     Visit adminmyapp/tag/. Edit and save the tag objects to generate slugs.


  •  Updating homepage template :-

     Edit myapp index.html file and use {% url 'tags' tag.slug %} to generate the link:

myapp/templates/myapp/index.html

<hr>

{% for tag in flower.tags.all %}

<a href="{% url 'tags' tag.slug %}" class="card-link">{{ t\

ag }}</a> <!-- here -->

{% endfor %}


     Now the frontpage tags link to the tags page:




     Click the tag links and you will see the according tag page: tagsrosales/. If you have Flowers tagged with “Rosales”, you will only see those items in this page:



  •  In Details :-

  •   Doing lookups across relationships :-

     In myapp views.py file we fetch objects that are tagged with a specific tag:

myapp/views.py

def tags(request, slug=None):

flowers = Flower.objects.filter(tags__slug=slug) # < he\

re

return render(request, 'myapp/index.html', {'flowers': \

flowers })


     With filter function you can return a QuerySet that match lookup parameters. In this case our parameter is tags__slug=slug. This will return all flower objects that has a reference to a tag object with the slug from the URL. tagsrosales/ would fetch all flowers tagged with “Rosales”.


     Django has plenty of other query interaction tools. See https://samuli.to/QuerySet-API.


  •  Reusing templates :-

     You might have noticed that we are using the same myapp index.html in the frontpage and in the tags page. Reusing templates will save you a lot of time and makes it easier to make changes. Now if we want to change the card styling or markup, we can do it in one place. The changes will show up in the frontpage and in the tags page.


Summary


  •  Django offers a big selection of methods like filter() to modify your data queries.
  •  You can do lookups through relationships using the double underscore (__) syntax: tags__slug=slug.
  •  Reusing templates will make your app look consistent and easier to maintain.


👈Episode 16(P).                                                                           Episode 18(P)👉

Share This Post

PRINT THIS POST

No comments:

Post a Comment

If you have any doubts. Please let me know.

Featured post

*Episode 1* MCQ for Govt. Job/ Private Job/ MNCs

  Topic:- One Word Substitution 1) Especially skilled in storytelling  Answer:- Raconteur 2) Fear of loneliness Answer:- Eremophobia  3) Usa...