简体   繁体   中英

Django CreateView field labels

I'm working on a project that has a Chapter, with each Chapter having a title, content, and order. I'd like to keep the field 'order' named as is, but have the field displayed in a CreateView as something else, like 'Chapter number'. The best information I've found recommends updating the "labels" attribute in the Meta class, but this isn't working for me.

This is what I'm using now, which doesn't work:

class ChapterCreate(CreateView):
    model = models.Chapter
    fields = [
        'title',
        'content',
        'order',
    ]

    class Meta:
        labels = {
            'order': _('Chapter number'),
        }

I've also tried using the 'label's attribute outside of Meta, but that didn't work either. Should I be using a ModelForm instead, or is there a correct way to do this?

The simplest solution in this case would be to set the verbose_name for your model field

class Chapter(models.Model):
    order = models.IntegerField(verbose_name= _('Chapter number'))

Note I have use IntegerField in this example, please use whatever type is required.

Even if it is an old subject, I think a way to do this now with Django 3.1 would be:

in views.py

class ChapterCreate(CreateView):
    model = models.Chapter
    form_class = ChapterForm

and in forms.py, define ChapterForm

class ChapterForm(ModelForm):
    class Meta:    
        model = models.Chapter
        fields = ('title', 'content','order') 
        labels = {
            'order': _('Chapter number'),
        }  

If you want different values for the verbose_name of the model field and the user-facing label of the form field, the quickest way might be to override the get_form(…) method of CreateView :

class ChapterCreate(CreateView):
    (...)

    def get_form(self, form_class=None):
        form = super().get_form(form_class)
        form.fields['order'].label = _('Chapter number')
        return form

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM