-2

I am working on a Django project and I want to retrieve the category name in my template like Adventure, Hiking.. but instead, it's displaying ids of the category like 1,2,3. Instead of displaying the name of the category. Can someone help me out with this?

{% for data in tourData %}
 {{data.category}}
{% endfor %}

models.py

class Tour(models.Model):
category_choices=[('1','Adventure'),('2','Trekking'),('3','Hiking')]
category=models.CharField(max_length=1,choices=category_choices,default='1')

view.py

def recommendations(request):
if request.method=='POST':
    contents=Tour.objects.all()
    category1= request.POST['category']  #Retrieves the category entered by the user
    category2=request.POST['place'] 
    tourData = Tour.objects.all().filter(category=category1,place=category2).order_by('-rating').values()
    context={
        'tourData':tourData
    }
    return render(request,"base/recommendations.html",context)
else:
   tourData=Tour.objects.all().order_by('-rating').values()
   context={'tourData':tourData
   }
   return render(request,"base/recommendations.html",context)
  • 1
    Does this answer your question? [Django: Display Choice Value](https://stackoverflow.com/questions/4320679/django-display-choice-value) – Abdul Aziz Barkat Aug 03 '22 at 14:35

1 Answers1

1

You need to use get_field_display in your template, i.e.

{{ data.get_category_display }}

This will show the second tuple value in your model choices rather than the first (the first is what actually goes into the database).

As an aside, I would recommend changing the format of your tourData variable from camelCase to snake_case - tour_data - it's more pythonic.

0sVoid
  • 2,547
  • 1
  • 10
  • 25
  • Side Note: Variables are generally written in both `camelCase` and `snake_case` in any language, but in Django, function based views are written in `snake_case` while class based in `PascalCase`, well the answer is right :) – Sunderam Dubey Aug 03 '22 at 13:49