0

我正在使用 django 1.4.5,我需要在用户配置文件中显示一个名为“uuid”的字段

这不是pk。

我听说过 ModelChoiceField 的 to_field_name ,但显然由于 django 核心中的内部错误,这不起作用。

有人设法显示不是 pk 字段的字段吗?

我试图使用这个补丁:https ://gist.github.com/drdaeman/5326761

但无济于事。

10倍

4

1 回答 1

1

就在文档中:

将调用模型的unicode方法来生成对象的字符串表示形式,以用于字段的选择;提供自定义表示,子类 ModelChoiceField 并覆盖 label_from_instance。此方法将接收模型对象,并应返回适合表示它的字符串。例如:

所以有两个选择:

# in your model
def __unicode__(self):
    return unicode(self.uuid)

或者,如果您需要保留不同的字符串表示形式会更好:

from django import forms

class UUIDChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return unicode(obj.uuid)

class FormWithUUIDChoiceField(forms.form):
    field1 = UUIDChoiceField(queryset=..., ...)
于 2013-06-10T20:40:48.183 回答