0

这个:

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函数来完成。

任何想法?谢谢!

4

2 回答 2

2

在您希望在标签中呈现的每个字段中设置verbose_name参数。Model例如:

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

   ...
于 2013-04-26T22:39:17.080 回答
1

您可以verbose_name按照 Paulo 的建议设置模型。

或者,如果您不想触摸您的模型,您可以在表单上明确定义您的字段。

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")
于 2013-04-27T02:30:44.593 回答