5

如何使表单中的外键字段只读,但在提交表单后仍允许该字段被识别为有效?根据 W3C,一旦提交表单,禁用的字段就会被忽略......使用下面的代码,我可以将字段设置为禁用,因此是只读的,但我的表单没有通过

    def __init__(self, *args, **kwargs):
       super(IssuesForm, self).__init__(*args, **kwargs)
       self.fields['vehicle'].widget.attrs['readonly'] = True

想法……?

4

4 回答 4

3

在许多其他解决方案似乎不起作用之后,我遇到了这个问题。这是我如何使用“隐藏”建议成功运行它的示例代码,以防它对其他人有帮助。

class EditExifForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(EditExifForm, self).__init__(*args, **kwargs)
        self.fields['image'].widget.attrs['hidden'] = True    # This is the solution
        # Setting as 'readonly' didn't make a difference
        # Setting as 'disabled' made the form not update the database

    class Meta:
        model = exif
        ...
于 2019-05-21T22:32:54.370 回答
2

我不知道 Django 或 Python 语法,但是,type="hidden" 的输入字段可能是您正在寻找的。如果您仍想使用禁用字段显示值,您也可以这样做,并依赖隐藏字段来获取实际值。

于 2009-07-09T18:39:44.660 回答
0

也许我可以尝试隐藏领域...我知道这是可能的,但我想确定没有其他方法

于 2009-07-09T18:45:29.203 回答
0

我遇到过这个问题,我用 JavaScript 来解决

于 2009-08-09T05:01:21.950 回答