2013-04-26 127 views
0

此:的ModelForm混亂

class ArticleForm(Form): 
     title = forms.CharField(label="Title", max_length=255,required=True) 
short = forms.CharField(label="Short Description",widget=Textarea(attrs={'rows':'4'}),required=True) 
     content = forms.CharField(label="Content",widget=Textarea(attrs={'rows':'20'}),required=True) 
     categories = forms.MultipleChoiceField(label="Audit Group",choices=[(o.id, o.real_name()) for o in AuditGroup.objects.all()], widget=forms.CheckboxSelectMultiple 

正在很好地呈現爲一個觀點 - 然後我意識到我需要一個ModelForm! ;)

但這:

class ArticleForm(ModelForm): 
    class Meta: 
     model = Article 
     fields = ("title","categories","topic","short_desc","content") 
     widgets = { 
      'short_desc':Textarea(attrs={"rows":'4'}) , 
      'content':Textarea(attrs={"rows":'20'}) , 
      'categories':CheckboxSelectMultiple(choices=[(o.id, o.real_name()) for o in AuditGroup.objects.all()]), 
      'topic':CheckboxSelectMultiple(choices=[(o.id, o.name) for o in Topic.objects.all()]) 
     } 

顯示不正確,我認爲標籤。這應該通過o.real_name()o.name函數完成。

有什麼想法?謝謝!

+0

你能後的模型定義?標籤被渲染? – 2013-04-26 22:36:55

回答

1

您可以按照Paulo的建議在您的模型上設置verbose_name

或者,如果您不想觸摸模型,則可以在窗體上明確定義您的字段。

class ArticleForm(ModelForm): 

    short_desc = forms.CharField(label="Short Description") 
    #similarly any change you want in other fields. 
    class Meta: 
     model = Article 
     fields = ("title","categories","topic","short_desc","content") 

另一種方式: 如果你不想重新定義表單字段,並只希望更改標籤,你可以做到這一點在__init__

class ArticleForm(ModelForm): 

    def __init__(self, *args, **kwargs): 
     super(ArticleForm, self).__init__(*args, **kwargs) 
     self.fields['short_desc'].label = "Short description" 
    class Meta: 
     model = Article 
     fields = ("title","categories","topic","short_desc","content") 
2

在您的每個Model的字段中設置verbose_name參數,因爲您希望在標籤中進行渲染。例如:

class Article(Model): 
    title = forms.CharField(verbose_name="Title", ...) 
    short = forms.CharField(verbose_name="Short Description", ...) 
    content = forms.CharField(verbose_name="Content", ...) 

    ...