Home > OS >  How do I make a form's Choice Field values show the actual values on a page instead of numbers?
How do I make a form's Choice Field values show the actual values on a page instead of numbers?

Time:07-31

There is a field (categories) in my form (NewListing) that should has 4 values that can be selected in a form on one of my pages. However, when I want to show which value was selected I get a number instead of the value.

The values are:

  • New
  • Refurbished
  • Opened
  • Used

So if New was selected earlier, when this value is shown on another page it is shown as 1 instead of New.

How do I fix this?

models.py:

class Listing(models.Model):
    ...
    condition = models.CharField(max_length=20)

forms.py:

condition_choices = (
    (1, 'New'),
    (2, 'Refurbished'),
    (3, 'Opened'),
    (4, 'Used'),
)

class NewListing(forms.Form):
    ...
    condition = forms.ChoiceField(choices=condition_choices, widget=forms.Select(attrs={
        'class': 'condition',
    }))

html: (irrelevant but shows where it would be used - it selected on another page though - this works fine)

<div >
    <p> Condition: <strong> {{ listing.condition }} </strong></p>
</div>

CodePudding user response:

Replace the elements in the tuple with human-friendly values.

CONDITION_CHOICES = [
    ('NEW', 'New'),
    ('REF', 'Refurbished'),
    ('OPE', 'Opened'),
    ('USE', 'Used'),
]
  • Related