2011-06-05 120 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