ModelForm混乱

时间:2013-04-26 22:07:37

标签: django templates django-forms

此:

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

有什么想法吗?谢谢!

2 个答案:

答案 0 :(得分: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", ...)

   ...

答案 1 :(得分: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")