alexander alexander - 1 month ago 13
Python Question

Django choices and dictionary

I have code

JOBS = 1
CATEGORY_CHOICES = ((JOBS, "Jobs"),)


And code in the model

category = models.IntegerField(choices=CATEGORY_CHOICES, default=JOBS)


Instead of "jobs" I want to add a dictionary and have access to it in the template. For example

JOBS = 1
CATEGORY_CHOICES = ((JOBS, {'title':"Jobs",'icon':"fa fa-briefcase",'slug':"jobs"}),)


But instead I get the following

enter image description here

How to add the dictionary into the choices?
I was able to create a model, which would be set up: title and icon. But instead, I decided to create a choice. Title I can add, but for the selected item to set the icon?

Answer

I would comment, but sadly not enough rep. The way IntegerField is setup, it displays the dictionary value and returns the dictionary key.

What it seems you want to do is have that key determine the results of several other values. What you should do then is in whatever view you submit that form to, set those other values based on the key returned by your IntegerField.

In other words:

CATEGORY_CHOICES = ((1, 'Jobs'),(2, 'Cities'),)

Then later in the class or view that this form is submitted to:

if CATEGORY_CHOICES  == 1:
    title = 'Jobs'
    icon = 'fa fa-briefcase'
    slug = 'jobs'
elsif CATEGORY_CHOICES == 2:
    title = 'Cities'
`   icon = 'fa fa-city'
    slug = 'cities'
Comments