为什么 Django 中的只读表单字段是个坏主意? [英] Why are read-only form fields in Django a bad idea?

查看:25
本文介绍了为什么 Django 中的只读表单字段是个坏主意?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一种创建只读表单字段的方法,我发现的关于该主题的每篇文章都附有这是一个坏主意"的声明.现在对于单个表单,我可以理解还有其他方法可以解决问题,但是在模型表单集中使用只读表单字段似乎是一个完全自然的想法.

考虑教师成绩簿申请,教师希望能够通过一次提交输入所有学生(注意复数学生)的成绩.模型集可以迭代所有学生成绩,学生姓名是只读的,成绩是可编辑的字段.我喜欢模型表单集错误检查和错误报告的强大功能和便利性,但让学生姓名在这样的表单集中可编辑是很疯狂的.

由于专家 django 的共识是只读表单字段是一个坏主意,我想知道上面的示例学生级示例的标准 django 最佳实践是什么?

解决方案

您不想这样做的原因是因为有人可以将您的禁用字段更改为启用,然后提交表单.您将不得不更改保存功能,以免插入禁用"数据.

执行此操作的标准方法是不将名称放入输入中,而是将其显示为文本

<div><label>名称</label><p>约翰尼五号</p>

<div>....

这在 django 中是不可能的.

我说如果你真的相信你的用户群不会搞砸",那就去吧,但如果它是一个面向公众的网站,可能有敏感数据,那就远离.

I've been looking for a way to create a read-only form field and every article I've found on the subject comes with a statement that "this is a bad idea". Now for an individual form, I can understand that there are other ways to solve the problem, but using a read only form field in a modelformset seems like a completely natural idea.

Consider a teacher grade book application where the teacher would like to be able to enter all the students' (note the plural students) grades with a single SUBMIT. A modelformset could iterate over all the student-grades in such a way that the student name is read-only and the grade is the editable field. I like the power and convenience of the error checking and error reporting you get with a modelformset but leaving the student name editable in such a formset is crazy.

Since the expert django consensus is that read-only form fields are a bad idea, I was wondering what the standard django best practice is for the example student-grade example above?

解决方案

The reason you don't want to do this is because someone can change your disabled field to enabled and then submit the form. You would have to change the save function as to not insert the "disabled" data.

The standard way to do this is to not put the name in an input, but to display it as text

<form>
    <div>
        <label>Name</label>
        <p>Johnny Five</p>
    </div>
    <div>
        ....

This is not possible in django.

I say if you really trust your userbase to not "mess" with things then go for it, but if its a public facing website with possible sensitive data then stay away.

这篇关于为什么 Django 中的只读表单字段是个坏主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆