Home > Net >  I want to get all the wallpapers who have similar name, tags to the wallpaper which is rendered
I want to get all the wallpapers who have similar name, tags to the wallpaper which is rendered

Time:01-10

views.py

def download(request, wallpaper_name):
    wallpaper = Wallpaper.objects.get(name=wallpaper_name)
    context = {'wallpaper': wallpaper}
    return render(request, 'Wallpaper/download.html', context)

models.py

class Tags(models.Model):
    tag = models.CharField(max_length=100)

wallpaper model

class Wallpaper(models.Model):
    name = models.CharField(max_length=100, null=True)
    size = models.CharField(max_length=50, null=True)
    pub_date = models.DateField('date published', null=True)
    resolution = models.CharField(max_length=100, null=True)
    category = models.ManyToManyField(Category)
    tags = models.ManyToManyField(Tags)

HTML

<ul>
   <li>{{wallpaper.name}}</li>
   {% for i in wallpaper.tags_set.all %}
     <li>{{i.tags}}</li>
   {% endfor %}
</ul>

urls.py

path('<wallpaper_name>/', views.download, name="download"),

Like example the wallpaper I have choosen to download has tags nature and ocean so I want all the wallpapers who have this tag

CodePudding user response:

It should be

<ul>
   <li>{{wallpaper.name}}</li>
   {% for i in wallpaper.tags.all %}
     <li>{{i.tags}}</li>
   {% endfor %}
</ul>

instead of

<ul>
   <li>{{wallpaper.name}}</li>
   {% for i in wallpaper.tags_set.all %}
     <li>{{i.tags}}</li>
   {% endfor %}
</ul>

CodePudding user response:

If you want to get Wallpapers similar to the one you have on basis of tags, you should use this library django-taggit.

This library's API has a method similar_objects().

This is how your wallpaper model would look like.

from taggit.managers import TaggableManager

class Wallpaper(models.Model):
    name = models.CharField(max_length=100, null=True)
    size = models.CharField(max_length=50, null=True)
    pub_date = models.DateField('date published', null=True)
    resolution = models.CharField(max_length=100, null=True)
    category = models.ManyToManyField(Category)
    tags = TaggableManager()

And in your views.py

def download(request, wallpaper_name):
    wallpaper = Wallpaper.objects.get(name=wallpaper_name)
    similar_wallpapers = wallpaper.tags.similar_objects()
    context = {'wallpaper': wallpaper, 'similar_wallpapers': similar_wallpapers}
    return render(request, 'Wallpaper/download.html', context)

HTML

<ul>
   <li>{{wallpaper.name}}</li>
   {% for wallpaper in similar_wallpapers %}
     <li>{{wallpaper.name}}</li>
   {% endfor %}
</ul>

This will list out the names of the wallpaper that have same or similar tags.

  •  Tags:  
  • Related