[英]How to set text in Django drop down menu?
Is it possible to set a label for each item of drop down menu? 是否可以为下拉菜单的每个项目设置标签? It shows
__str__
outputs from the module instances - items from table. 它显示了模块实例的
__str__
输出-表中的项目。
class LanguageDropDownForm(forms.Form):
languages = forms.ModelChoiceField(queryset=Languages.objects.all().order_by('language_shortcut'))
Models.py: Models.py:
class Languages(models.Model):
language = models.CharField(max_length=100)
language_shortcut = models.CharField(max_length=3)
price_per_word = models.FloatField()
def __str__(self):
return 'SC: {} Lang: {} PPW: {}'.format(self.language_shortcut,self.language,self.price_per_word)
Could you give me an advice? 你能给我个建议吗?
I want for example just model.language
or model.name
instead of __str__
method which is useful for example in admin
. 我只想使用
model.language
或model.name
而不是__str__
方法,例如admin
。
Yea. 是啊。 Just use unicode instead of what you got there.
只需使用unicode而不是您所到之处。
def __unicode__(self):
As the doc says, you should inherit the default ModelChoiceField
for languages field and override label_from_instance
method: 如文档所述 ,您应该继承默认的语言字段的
ModelChoiceField
并覆盖label_from_instance
方法:
class LanguageModelChoiceField(forms.ModelChoiceField):
def label_from_instance(self, obj):
return 'SC: {} Lang: {} PPW: {}'.format(obj.language_shortcut,
obj.language,
obj.price_per_word)
Then in your form you do: 然后以您的形式执行:
class LanguageDropDownForm(forms.Form):
languages = LanguageModelChoiceField(queryset=Languages.objects.all().order_by('language_shortcut'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.