python - Django pass model to widget in ModelForm
问题描述
I have a ModelForm
that has an extra field that is a custom widget. I can add an extra field with a widget and pass arbitrary key values to it when constructing the widget. I'm also able to access model data within the ModelForm
in the __init__
function.
My problem lies in that adding an extra field in the ModelForm
requires doing so outside the __init__
function while accessing model data is only possible from within the __init__
function.
class SomeForm(forms.ModelForm):
title = None
def __init__(self, *args, **kwargs):
some_data = kwargs['instance'].some_data
# ^ Here I can access model data.
super(SomeForm, self).__init__(*args, **kwargs)
self.fields['some_extra_field'] = forms.CharField(widget= SomWidget())
# ^ This is where I would pass model data, but this does not add the field.
class Meta:
model = Page
fields = "__all__"
some_extra_field = forms.CharField(widget= SomeWidget())
# ^ I can add a field here, but there's no way to pass some_data to it.
I've also tried setting self.some_data
in __init__
, but it's still not accessible when I try to use self.some_data
when setting some_extra_field
at then end of the class.
How should pass model data to a widget in a ModelForm
?
解决方案
If I'm following what you need correctly, you can do this simply by editing or reassigning the widget in __init__
. Something like:
class SomeForm(forms.ModelForm):
title = None
def __init__(self, *args, **kwargs):
some_data = kwargs['instance'].some_data
super(SomeForm, self).__init__(*args, **kwargs)
# Pass whatever data you want to the widget constructor here
self.fields['some_extra_field'].widget = SomWidget(foo=...))
# or possibly (depending on what you're doing)
self.fields['some_extra_field'].widget.foo = ...
推荐阅读
- python - 将相关性的负结果与 ppscore 进行比较
- python - TensorFlow tensor_scatter_nd_add 索引
- java - Card Layout 可以显示 Card Layout
- postgresql - 将来自 JSON 数组对象字段的数据与另一个表连接起来
- linux - 当某些条件为真时,使用“sed”对两个连续的行重新排序
- python - 从 Django 模型获取 chart.js 的动态数据
- python - 使用带有默认条件的 sklearn2pmml 将决策树转换为 PMML
- ssh - 使用 ZeroTier 网络的 SSH 隧道
- visual-studio-code - VS Code - 有没有办法计算项目中的所有代码行?
- amazon-web-services - AWS 加载客户端凭证