简体   繁体   English

Django CreateView 字段标签

[英]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'.我想保持字段“订单”的名称不变,但在 CreateView 中将该字段显示为其他内容,例如“章节编号”。 The best information I've found recommends updating the "labels" attribute in the Meta class, but this isn't working for me.我发现的最佳信息建议更新 Meta class 中的“标签”属性,但这对我不起作用。

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.我也尝试过在 Meta 之外使用“标签”属性,但这也不起作用。 Should I be using a ModelForm instead, or is there a correct way to do this?我应该改用 ModelForm,还是有正确的方法来做到这一点?

The simplest solution in this case would be to set the verbose_name for your model field在这种情况下,最简单的解决方案是为您的模型字段设置verbose_name

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.注意我在这个例子中使用了 IntegerField,请使用任何需要的类型。

Even if it is an old subject, I think a way to do this now with Django 3.1 would be:即使它是一个古老的主题,我认为现在使用 Django 3.1 做到这一点的方法是:

in views.py在views.py中

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

and in forms.py, define ChapterForm并在 forms.py 中,定义 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 :如果您想要 model 字段的verbose_name和表单字段的面向用户的 label 的不同值,最快的方法可能是覆盖CreateViewget_form(…)方法:

class ChapterCreate(CreateView):
    (...)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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