0

I'm new in django/python, so please bear with me.

I want to create some sort of "Related Post" in django. How I can do that? I'm following this : How to fetch related items when using taggit in django?

but dont know how to use/implement it and how to render it in template. This is my view :

def trip_list(request):
    trip_list = Trip.objects.filter(misc_published=True).order_by('-misc_published')[:12]
    related = Trip.objects.filter(tags=trip_list.tags.similar_objects())[:3]
    return render(request, 'app_trip/trip_list.html', {'trip_list': trip_list})

Any help would be greatly appreciated!

Thank you

----------- UPDATE -----------

Okay, after babling with the code, it seems it's almost success, but it's error :

ValueError at /trip/tour-island/

Cannot query "bali island Tour": Must be "Tag" instance.

Here is my updated code :

def trip_single(request, slug):
    trip = get_object_or_404(Trip, slug=slug)
    trip_related = Trip.objects.filter(misc_published=True, tags=trip.tags.similar_objects())[:3]
    return render(request, 'app_trip/trip_single.html', {'trip': trip}, {'trip_related': trip_related})

In the template

{% for trip in trip_related %}
   <h1>{{ trip.title }}</h1>
{% endfor %}

Thank you

----------- UPDATE [SOLVED!] -----------

Using model_name.tags.similar_objects()

In views.py :

def trip_single(request, slug):
    trip = get_object_or_404(Trip, slug=slug)
    trip_related = trip.tags.similar_objects() # Where the magic happen
    return render(request, 'app_trip/trip_single.html', {'trip': trip, 'trip_related': trip_related})

In template :

{% for trip in trip_related %}
    <h1>{{ trip.trip_judul }}</h1>
{% endfor %}

Thanks!

Community
  • 1
  • 1

1 Answers1

0

similar_objects is returning a trip list, you can write this sentence:

trip_related = [a_trip 
                for a_trip in trip.tags.similar_objects() 
                if a_trip.misc_published
               ][:3]
dani herrera
  • 48,760
  • 8
  • 117
  • 177
  • Hi, thanks for the reply. The error is gone, but still it shows nothing. I expect something like loop, but it's related post/item. Here is my code : https://pastebin.com/WG2ExtPH (I cannot format my code here). Thank you! – alzea arafat May 02 '17 at 01:45