python - 在表单中将初始化的外键字段设置为只读

标签 python django forms foreign-keys readonly

我的表单中有一个外键字段,初始化为:

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/

相关文章:

python - 运行 heroku run 命令会生成 SECRET_KEY 设置不能为空错误

Django在查询/注释中格式化DecimalField

php - 提交表单后如何在不选择要上传的新图像的情况下保留以前上传的图像(在db中)

php - AJAX 联系表单发送空参数?

python - 如何在 USB 闪存中创建 Python 虚拟环境

python - 异步 : keep multiple coroutines running

Python 何时使用 OOP 何时不使用 OOP

django - 如何使用 google smtp 服务器从 django 发送电子邮件?

python - 我什么时候应该使用 'path' 而不是 're_path' ?

forms - 在 RoR 中,f.fields_for 渲染为空