Yian
Yian

Reputation: 199

Show Integer choice value as Characters (not integer) in Admin

I'm trying to display values from a choices field. Using the below methods, causes the "Store" model to break (clicking on it from Admin)

Error is:

TypeError __str__ returned non-string (type int)

When I change str to int the error stops- but it doesn't display the region choice (just "Region Object").

country_list = ['Global', 'Australia', 'United Kingdom', 'United States']

Region_CHOICES = tuple(enumerate(country_list, start=1))

class Region (models.Model):
    region = models.IntegerField(choices=Region_CHOICES)
    def __str__(self):
        return self.region

class Store(models.Model):
    store_name = models.CharField(max_length=30)
    region = models.ManyToManyField(Region, blank=True)

How can I get it to correctly return the Region as a choice (from the list of words, not the integer itself)?

Upvotes: 1

Views: 1746

Answers (2)

M Ashraful A
M Ashraful A

Reputation: 637

Just type cast to string

def __str__(self):
    return str(self.region)

This works for me

Upvotes: 0

dursk
dursk

Reputation: 4445

The issue is that your __str__ method must return an object of type str.

Since the index is what's stored in self.region, you can simply do a lookup:

class Region(models.Model):
    ...
    def __str__(self):
        return Region_CHOICES[self.region][1]

Upvotes: 2

Related Questions