views:

88

answers:

4

I want to show the human-readable name for the type selected but I keep getting the stored value.

TYPE_CHOICES = (
    ('0', 'Basic'),
    ('1', 'Full'),
    ('2', 'Intermediate'),
)

class ServiceType(models.Model):
       type = models.IntegerField(max_length=1, choices=TYPE_CHOICES)
       amount = models.DecimalField(max_digits=10, decimal_places=2)

       def __unicode__(self):
            return '%s' % (self.get_type_display()) 
+1  A: 

I had that same problem, and couldn't figure out why it works, but if you change the field type to CharField the get_type_display should work fine.

TYPE_CHOICES = (
  ('B', 'Basic'),
  ('F', 'Full'),
  ('I', 'Intermediate'),
)

class ServiceType(models.Model):
   type = models.CharField(max_length=1, choices=TYPE_CHOICES)
   amount = models.DecimalField(max_digits=10, decimal_places=2)
mountainswhim
+2  A: 

You probably want to use ChoiceField instead of IntegerField in your model. It sounds like you are seeing an input tag with type=text in your admin but want a select tag. The default widget associated with a IntegerField is TextInput which would explain what you are seeing.

Another option is to write your own admin and explicitly call out that you want type to be a ChoiceField in the admin. Something like this:

class ServiceTypeAdmin(admin.ModelAdmin):
    # ...
    type = fields.ChoiceField(choices=TYPE_CHOICES)

admin.site.register(ServiceType, ServiceTypeAdmin)

I would personally start by switching the IntegerField to a ChoiceField. Way less work involved.

istruble
A: 

Rookie mistake, I've changed the tuple values from ('0', 'Basic) to (0, 'Basic') and it worked. I didn't realize that I was saving a char value as an integer value.

Thanks for your help.

mF
+1  A: 

It seems that you have your answer, but as another link, I'd just like to point out James Bennett's thoughts on this: Handle choices the right way

I think it is a pretty convenient way to do things, and removes the 'magic number' aspect of things. Worth a read IMO, even if you go for a different option.

From his article (quoted in case it disappears):

class Entry(models.Model):
    LIVE_STATUS = 1
    DRAFT_STATUS = 2
    HIDDEN_STATUS = 3
    STATUS_CHOICES = (
        (LIVE_STATUS, 'Live'),
        (DRAFT_STATUS, 'Draft'),
        (HIDDEN_STATUS, 'Hidden'),
    )
    # ...some other fields here...
    status = models.IntegerField(choices=STATUS_CHOICES, default=LIVE_STATUS)

Now we can just import the Entry model and query like so:

live_entries = Entry.objects.filter(status=Entry.LIVE_STATUS)
draft_entries = Entry.objects.filter(status=Entry.DRAFT_STATUS)
DrBloodmoney
Thanks!, I'll change that. I've followed the blog project of Practical Django Projects and now I remember that code. I guess reading a book code without coding yourself a personal project it's not the best for me.
mF