You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

wagtailstreamforms自定义字段的width参数如何在Django模板中读取

修复方案

步骤1:修正字段定义代码

你在wagtailstreamforms_fields.py中额外写的get_formfield方法是多余且错误的,覆盖了父类默认逻辑,导致自定义的width参数没有被传入自定义字段类的构造函数。直接删除该方法即可,修正后代码如下:

from django import forms
from wagtailstreamforms.fields import BaseField, register
from wagtail.core import blocks

class CustomCharField(forms.CharField):
    def __init__(self,*args, **kwargs):
        self.width = kwargs.pop('width')
        super().__init__(*args,**kwargs)

@register('singleline')
class Column_SingleLineTextField(BaseField):
    field_class = CustomCharField

    def get_options(self, block_value):
        options = super().get_options(block_value)
        options.update({'width': block_value.get('width')})
        return options

    def get_form_block(self):
        return blocks.StructBlock([
            ('label', blocks.CharBlock()),
            ('help_text', blocks.CharBlock(required=False)),
            ('required', blocks.BooleanBlock(required=False)),
            ('default_value', blocks.CharBlock(required=False)),
            ('width', blocks.IntegerBlock(help_text="Width of field, 1 to 12, 12 is full width.", max_value=12, min_value=1, default=12, required=True)),
        ], icon=self.icon, label=self.label)

父类BaseField的默认get_formfield方法会自动调用你重写的get_options拿到包含width的参数,再传入你定义的CustomCharField完成实例化,无需你手动重写。

步骤2:修正模板取值逻辑

Django模板中遍历表单得到的field是BoundField包装对象,你自定义的width属性存放在它的field属性(即你定义的CustomCharField实例)中,所以要加一层.field访问。修改templates/partials/custom_form_field.html代码如下:

{% load form_tags %}

<div class="col-{{ field.field.width }}">
    {{ field.label_tag }}
    {{ field }}
    {{ field.field.width }}
    <p>{% dict field %}</p>
    {% if field.help_text %}<p class="help-text">{{ field.help_text }}</p>{% endif %}
    {{ field.errors }}
</div>

内容的提问来源于stack exchange,提问作者SidS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 02:18:04