python - Django Forms - Is 'readonly' safe to use?
问题描述
I created a form in Django. In this form, there is a field that must not be edited by the user, because the default value of the form must be sent to my database as it is. I come up with the following solution, but after making some research, i've come to find that using readOnly
is generally not a good idea.
Can someone clarify me on this? Should i go with another solution?
tst = forms.CharField(
initial='//value to be sent to the db without being touched',
widget=forms.TextInput(attrs={'readonly':'readonly'}))
解决方案
否:因为这只是客户端的一个属性。但是用户可以简单地绕过它。例如,通过在没有浏览器的情况下发出 POST 请求,或者readonly
通过操作 DOM 来更改属性。
从django-1.9 开始,您可以使用该disabled=...
参数。这不仅会禁用 HTML 元素,还会省略具有该名称的 GET/POST 参数,如文档所述:
disabled
布尔参数,当设置为 时,True
使用disabled HTML 属性禁用表单字段,以便用户无法编辑它。即使用户篡改了提交给服务器的字段值,它也会被忽略,取而代之的是表单初始数据中的值。
因此,您可以使用以下方式实现您的表单:
class MyForm(forms.ModelForm):
tst = forms.CharField(
initial='//value to be sent to the db without being touched',
disabled=True,
widget=forms.TextInput)
)
请注意,如果您只打算分配一个值,则应从表单中省略该字段,并仅在模型中分配它。
推荐阅读
- android-studio - 将 build.gradle 从 2.3.3 更新到 3.4.1,但我仍然收到重新“编译”被“实现”替换的警告?
- python - 有没有办法优雅地在圆圈内绘制箭头
- ios - KeyboardLayoutGuide 在 iMessage 应用程序中不起作用
- c# - 如何修复此 2D 控制器代码,以便我的游戏对象立即以 100% 的速度运行?
- r - 如何使用 lapply 在 Shiny 中创建反应对象?
- reactjs - 如何使用 Spectron 选择 React 组件?
- docker - Dockerfile 的构建挂起或需要很长时间?
- mongodb - 在 MongoDb 中创建嵌套聚合集
- javascript - 下拉列表不起作用...未从数据库添加到列表的值以及选择显示输出的值以供显示
- javascript - 颜色选择器组件在 Vuetify 模态中不像在整页上那样工作