【问题标题】:How to get help_text on a custom Django ModelChoiceField如何在自定义 Django ModelChoiceField 上获取 help_text
【发布时间】:2018-11-02 22:42:52
【问题描述】:

我正在创建一个customModelChoiceField,这样我就可以为我的外键显示自定义标签,但是这样做Django 不再在表单上显示help_text。如何取回帮助文本?

models.py

class Event(models.Model):

    title = models.CharField(max_length=120)
    category = models.ForeignKey(Category, default=Category.DEFAULT_CATEGORY_ID, on_delete=models.SET_NULL, null=True,
                                 help_text="By default, events are sorted by category in the events list.")

forms.py

class CategoryModelChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return "%s (%s)" % (obj.name, obj.description)

class EventForm(forms.ModelForm):

    category = CategoryModelChoiceField(
        queryset=Category.objects.all(),
    )

    class Meta:
        model = Event
        fields = [...]

【问题讨论】:

  • help_text 作为参数传递给CategoryModelChoiceField。也许您可以像 help_text=self._meta.model.category.help_text 或类似的东西访问它。

标签: python django modelform modelchoicefield


【解决方案1】:

在问题下方评论的帮助下,以下是我获取自定义表单字段以从模型中获取默认帮助文本的方法:

class EventForm(forms.ModelForm):
    category = CategoryModelChoiceField(
        queryset=Category.objects.all(),
        help_text=Event._meta.get_field('category').help_text,
)

【讨论】:

    【解决方案2】:

    你可以在Meta里面添加。

    from django.utils.translation import gettext_lazy as _
    
    class AuthorForm(ModelForm):
        class Meta:
            model = Author
            fields = ('name', 'title', 'birth_date')
            labels = {
                'name': _('Writer'),
            }
            help_texts = {
                'name': _('Some useful help text.'),
            }
            error_messages = {
                'name': {
                    'max_length': _("This writer's name is too long."),
                },
            }
    

    django docs

    另外,您可以使用__init__ 方法添加。

    class EventForm(forms.ModelForm):
    
        def __init__(self, *args, **kwargs):
            super(EventForm, self).__init__(*args, **kwargs)
            self.fields['category'].help_text = ''
    

    【讨论】:

    • 如何获取模型字段中已经存在的帮助文本?
    猜你喜欢
    • 2012-03-28
    • 2016-08-28
    • 1970-01-01
    • 2013-11-22
    • 2016-06-20
    • 2011-09-14
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多