python - Django Forms - 'readonly' 使用安全吗?

标签 python django django-forms django-templates

我在 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 属性。

,您可以使用disabled=...范围。这不仅会禁用 HTML 元素,还会省略具有该名称的 GET/POST 参数,如文档中所述:

The disabled boolean argument, when set to True, 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/

相关文章:

python - 使用Python实时访问简单但大的数据集

javascript - 如何在 Django 中使用 jQuery?

python - Django 模板中的时区感知日期时间对象

Python/Django 在 Heroku 上的 gunicorn 上崩溃

django - 我可以创建一个表单和 View 的文件夹并使用 __init__.py 文件(如模型和测试)吗?

django - 使用FormView django在form_valid中渲染模板而不是success_url

python - 注释 'xy'与模型上的字段冲突-django

python - 如何根据 Pyspark 中的正则表达式条件验证(和删除)列,而无需多次扫描和洗牌?

django - 如何使用地理位置 API 向用户位置提供默认点域值,无法将字符串转换为 float :

python - Upstart python脚本