2011-06-05 53 views
0

不知道如何在ModelChoiceField更新标签ModelChoiceField标签是不正确

型号:

class Category(models.Model): 

    categoryText = models.CharField(max_length=50) 
    parentCat = models.ForeignKey('self',null=True,blank=True) 

形式:

class CategoryForm(forms.Form): 
    category = forms.ModelChoiceField(queryset=Category.objects.all()) 

现在,当我展示的形式,我得到“类别对象“作为下拉标签。我喜欢将标签更改为categoryText中存储的内容。

我如何做到这一点?

回答

2
class Category(models.Model): 
    categoryText = models.CharField(max_length=50) 
    parentCat = models.ForeignKey('self',null=True,blank=True) 

    def __unicode__(self): 
     return self.categoryText 

Unicode的方法由Django的内部使用,当它想要的打印的特定模型对象/表格行的人类友好的版本(在管理,或作为一种形式的标签例如)。您应该为您创建的每个模型编写一个unicode方法。

Here is django's entry about the unicode function

+0

它的工作 - 感谢 刚才知道为什么它的工作。 我可以用__init__做到吗? – afshin 2011-06-05 02:14:33

+1

'__unicode__'是由Django(和Python一般)调用的方法,用于生成类的实例的字符串表示形式。在这种情况下,它只是返回其'categoryText'字段的值。 – vicvicvic 2011-06-05 02:54:24

+0

,所以尝试使用init来做没有意义。如果您的问题得到解答,请点击左侧选票旁边的绿色箭头接受答案 – 2011-06-05 10:58:48