首页 > 解决方案 > 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'}))

标签: pythondjangodjango-formsdjango-templates

解决方案


:因为这只是客户端的一个属性。但是用户可以简单地绕过它。例如,通过在没有浏览器的情况下发出 POST 请求,或者readonly通过操作 DOM 来更改属性。

,您可以使用该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)
    )

请注意,如果您只打算分配一个值,则应从表单中省略该字段,并仅在模型中分配它。


推荐阅读