迁移自定义字段渲染器从Django 1.8到Django 3.2

huangapple go评论62阅读模式
英文:

Migrate Custom Field Renderer from Django 1.8 to Django 3.2

问题

我正在尝试将Django 1.8表单中的自定义字段渲染器迁移到Django 3.2。

该表单如下所示:

class SomeEditForm(forms.ModelForm):
    job_uuid=forms.CharField(widget=forms.HiddenInput())
    class Meta:
        model=Job
        fields=('status',)
        widgets={'status': forms.RadioSelect(renderer=BSRadioFieldRenderer)}

看起来似乎不再有Rendermixin,它不再在def __init__()中接受渲染器。我已经阅读了新的源代码,看到RadioSelect现在是ChoiceWidget的子类。我无法弄清楚如何将我的旧渲染器嵌入到新结构中。

有人能指导我正确的方向吗?

感谢您的帮助! 迁移自定义字段渲染器从Django 1.8到Django 3.2

英文:

I am trying to migrate a custom field renderer in a Django 1.8 form to Django 3.2.

The form looks like this:

class SomeEditForm(forms.ModelForm):
    job_uuid=forms.CharField(widget=forms.HiddenInput())
    class Meta:
        model=Job
        fields=('status',)
        widgets={'status': forms.RadioSelect(renderer=BSRadioFieldRenderer)}

So as it seems there is no Rendermixin anymore which accepts a renderer in its def init(). I have read the new source code and see that RadioSelect is now a subclass of ChoiceWidget. I cant get my head around to inject my old renderer into the new structure.

Can someone please point me into the right direction?

Thanks for your help! 迁移自定义字段渲染器从Django 1.8到Django 3.2

答案1

得分: 0

这似乎有一种可行的方法...
只需继承 forms.RadioSelect 并接受像这样的 renderer 参数:

class CustomRadioSelect(forms.RadioSelect):
    def __init__(self, renderer=None, *args, **kwargs):
        super(forms.RadioSelect, self).__init__(*args, **kwargs)

class SomeEditForm(forms.ModelForm):
    job_uuid = forms.CharField(widget=forms.HiddenInput())
    class Meta:
        model = Job
        fields = ('status',)
        widgets = {'status': CustomRadioSelect(renderer=BSRadioFieldRenderer)}

请注意,这些类已经被截断,我只在这里写入了与我遇到的问题相关的部分。

英文:

There seems to be a hacky way which works...
Just subclass forms.RadioSelect and accept the renderer kwarg like this:

class CustomRadioSelect(forms.RadioSelect):
    def __init__(self, renderer=None, *args, **kwargs):
        super(forms.RadioSelect, self).__init__(*args, **kwargs)

class SomeEditForm(forms.ModelForm):
    job_uuid=forms.CharField(widget=forms.HiddenInput())
    class Meta:
        model=Job
        fields=('status',)
        widgets = {'status': CustomRadioSelect(renderer=BSRadioFieldRenderer)}

Please note that these classes are truncated and I only wrote those parts in here which are relevant to the problem I had.

huangapple
  • 本文由 发表于 2023年3月7日 04:43:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75655643.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定