【问题标题】:Display the selected item, not the number显示所选项目,而不是数字
【发布时间】:2012-04-07 11:12:02
【问题描述】:

Django python问题:选择下拉菜单返回item的数值。我不知道如何获取它的文本值。

模型.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") -->

【问题讨论】:

    标签: python html django django-forms django-templates


    【解决方案1】:

    您的模型有一个方法 get_profile_type_display 用于此目的:https://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 是您要查找的数值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多