andilabs
andilabs

Reputation: 23291

How to force django ModelForm to use `verbose_name` from the model as a label?

Code snippet:

[models.py]

class News(models.Model):
    title = models.TextField(verbose_name=u"Tytuł")

[forms.py]

class NewsForm(forms.ModelForm):
    title = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'form-input'}), required=True)
    class Meta:
        model = News
        fields = (
            'title',
        )

how to force label in form to use verbose_name and not title

I guess it is possible to link it in each field via label=here_some_geeky_way_of_accessing_fields_meta_and_greping_verbose_name but I think it should be possible somehow in more easy way...

Upvotes: 2

Views: 2416

Answers (1)

catavaran
catavaran

Reputation: 45575

If you want to override the default widget for the field then you can use the widgets property of the form's meta:

class NewsForm(forms.ModelForm):

    class Meta:
        model =News
        fields = ('title', )
        widgets = {
            'title': forms.TextInput(attrs={'class': 'form-input'}),
        }

In this case you don't need to re-define the form field. ModelForm will obtain the verbose name and the required flag from the model definition.

Upvotes: 2

Related Questions