Home > Software design >  How to pass a particular value inside a Tuple that also a tuple in Python in Django?
How to pass a particular value inside a Tuple that also a tuple in Python in Django?

Time:11-11

I have this dictionary for Categories that's a tuple within a tuple however I want to isolate only the literals --> the category names

from django.db import models

CATEGORIES = (
    ('a', 'Clothing'),
    ('b', 'Electronics'),
    ('c', 'Furniture'),
    ('d', 'Kitchen'),
    ('e', 'Miscellaneous'),
    ('f', 'None'),
)

but in a different file that's views.py is this

def show_category_listings(request, category):
    listings = Listing.objects.filter(category__in = category[0])
    cat = dict(CATEGORIES)
    return render(request, 'auctions/categSpecific.html', {
        "listings": listings,
        "category": cat[category]
    })

and finally in the html is this <li>Category: {{ listing.category }}</li> but what i see is only letters instead of the names look in html

is there a way to get only the category names? i couldn't figure out the passing of values in the views.py part.

CodePudding user response:

There are some magic methods in Django. One is get_FOO_display (), which displays a field value in a human-readable format.

Next code displays the name value in a choiceField.


<li>Category: {{ listing.get_category_display }}</li>

Read the docs here: https://docs.djangoproject.com/en/3.2/ref/models/instances/#django.db.models.Model.get_FOO_display

CodePudding user response:

Pass this in the template?

"category_names" : [ x[1] for x in CATEGORIES]

or even

"category_lookup" : { x[0]:x[1] for x in CATEGORIES }

Also see the documentation (get_FOO_display() ). Django models include methods to translate from the model field value to the human readable form. You can invoke this model method from a template as

{{ instance.get_fieldname_display }} 
  • Related