2012-03-22 32 views
0

Django python問題:選擇下拉列表返回項目的數值。我無法弄清楚如何獲取它的文本值。顯示選擇的項目,而不是數字

Models.py

profile_types = (('0', "Yadda"), ('1', "Frank and beans"), ('2', "Type"), ('3', "Placeholder"),\ 
       ('4', "Another"), ('5', "And another"), ('6', "aaand another"),\ 
       ('7', "Another"), ('8', "Last Type")) 

class Profile(models.Model): 
    user = models.ForeignKey(User, null=True, unique=True) 
    profile_types = models.CharField(max_length=2, choices=profile_types) 

Forms.py

class EditProfileForm(forms.Form): 
    profile_types = (('0', "Yadda"), ('1', "Frank and beans"), ('2', "Type"), ('3', "Placeholder"),\ 
        ('4', "Another"), ('5', "And another"), ('6', "aaand another"),\ 
        ('7', "Another"), ('8', "Last Type")) 
    name = forms.CharField(max_length=100, required=False, widget=forms.TextInput(attrs={'class':'input-text'})) 
    about = forms.CharField(widget=forms.Textarea(attrs={'class':'input-text'}), required=False) 
    org_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class':'input-text'})) 
    org_type = forms.CharField(max_length=8, widget=forms.Select(choices=choices)) 
    profile_type = forms.CharField(max_length=4, widget=forms.Select(choices=choices)) 

模板:

<span>{{ profile.profile_type }}</span> 

它返回

1 <-- (I'm trying to display "Frank and beans") --> 

回答

2

你的模型對於這個目的的方法get_profile_type_displayhttps://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.get_FOO_display

順便說一句,如果你想你也可以通過選擇搜索,或者使用dict(profile_types)[b for a,b in profile_types if a == test_value]其中test_value是你正在尋找的數值。

+1

完美。謝謝。 – Modelesq 2012-03-22 20:54:06

+0

@Modelesq沒問題! – Marcin 2012-03-22 20:55:09

相關問題