Django CreateView field labels
Asked Answered
I

3

6

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?

Incomer answered 7/11, 2016 at 22:36 Comment(0)
O
16

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.

Orthotropic answered 7/11, 2016 at 22:59 Comment(2)
Awesome, that did it and it's nice and easy. Thank you very much!Incomer
glad to have helpedOrthotropic
C
2

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
Chattanooga answered 18/8, 2022 at 9:45 Comment(0)
B
1

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'),
        }  
Ballon answered 15/11, 2020 at 15:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.