我在 Django 中创建了一个表单。在这个表单中,有一个字段不能由用户编辑,因为表单的默认值必须按原样发送到我的数据库。我提出了以下解决方案,但经过一些研究后,我发现使用 readOnly
通常不是一个好主意。
有人可以向我解释一下吗?我应该采用其他解决方案吗?
tst = forms.CharField(
initial='//value to be sent to the db without being touched',
widget=forms.TextInput(attrs={'readonly':'readonly'}))
最佳答案
否:因为这只是客户端的一个属性。但用户可以简单地绕过它。例如,通过在没有浏览器的情况下发出 POST 请求,或者通过操作 DOM 来更改 readonly
属性。
自 django-1.9 ,您可以使用disabled=...
范围。这不仅会禁用 HTML 元素,还会省略具有该名称的 GET/POST 参数,如文档中所述:
The
disabled
boolean argument, when set toTrue
, disables a form field using the disabled HTML attribute so that it won’t be editable by users. Even if a user tampers with the field’s value submitted to the server, it will be ignored in favor of the value from the form’s initial data.
所以你可以用以下方式实现你的表单:
class MyForm(forms.ModelForm):
tst = forms.CharField(
initial='//value to be sent to the db without being touched',
<b>disabled=True</b>,
widget=forms.TextInput)
)
请注意,如果您只打算分配一个值,则应从表单中省略该字段,而只在模型中分配它。
关于python - Django Forms - 'readonly' 使用安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57147358/