我的表单中有一个外键字段,初始化为:
form=myform(intial= {'val':abc.objects.get(pk=id)})
我已经单独尝试了以下一组代码,使字段“val”成为只读值。
form.fields['val'].widget = forms.HiddenInput()
form.fields['val'].widget.attrs['readonly'] = True
form.fields['val'].widget.attrs['disabled'] = True
form.fields['val'].widget.attrs['disabled'] = 'disabled'
form.fields['val'].widget.attrs['disabled'] = False
form.fields['val'].widget.attrs['display_only'] = True
form.fields['val'].widget.attrs['editable'] = False
只有 HiddenInput
有效,但它没有在表单中显示字段,而 disabled
显示错误。 readonly
适用于除外键字段之外的所有字段。
最佳答案
我通过覆盖 Select widgets 渲染方法并更改其输出来做到这一点。
class ReadOnlySelect(Select):
"""
This should replace the Select widget with a disabled text widget displaying the value,
and hidden field with the actual id
"""
def render(self, name, value, attrs=None, choices=()):
final_attrs = self.build_attrs(attrs, name=name)
display = "None"
for option_value, option_label in chain(self.choices, choices):
if str(option_value) == (value) :
display = option_label
output = format_html('<input type=text value="%s" disabled="disabled" ><input type="hidden" value="%s" %s> ' % (display, value, flatatt(final_attrs)))
return mark_safe(output)
关于 Django 片段的完整示例。 https://djangosnippets.org/snippets/10436/
关于python - 在表单中将初始化的外键字段设置为只读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12902365/