如何防止Django用户在不同会话中两次填写表单

huangapple go评论84阅读模式
英文:

How to restrict Django users from filling a form twice in different sessions

问题

我有一个供员工填写个人资料的表格,我想限制员工只能查看表格一次。

也就是说,在填写表格后,您将无法再查看空白表格,只能使用更新链接来更新表格。

我在用户注册和登录页面中使用了Django的is_authenticated函数,我正在寻找一种类似的方法来解决当前的问题。

英文:

I have a form for employees to fill their bio data, I want to restrict the employees from viewing the form more than once.

That is after filling the form, you can’t view the empty form anymore, you can only follow an update link to update the form.

I used the Django is_authenticated function for the user registration and login pages, I am looking for a way to do something similar for my current issue.

答案1

得分: 1

由于您试图在不同会话之间保持表单提交,您可以将此信息存储在数据库中,或者考虑将此信息存储在Redis中。这里我假设您将使用数据库。

您可以在现有的Employee模型中跟踪这些信息,或者如果您知道您可能需要扩展到其他表单,可以创建一个单独的模型。

这里我使用一个单独的模型来跟踪这些信息(如果存在一行,表示表单已经填写):

class EmployeeFormSubmission(models.Model):
    employee = models.OneToOneField(User, on_delete=models.CASCADE)

如果要跟踪多个表单,您可以添加另一个字段,如form_name

最后,您可以像这样检查当前员工是否已经提交了表单,并根据您的业务逻辑处理您真正想要做的事情(我在代码注释中指出了这一点):

if EmployeeFormSubmission.objects.filter(employee=request.user).exists():
   # 您可以在这里显示错误,或在视图中重定向以编辑信息。
else:
   # 这是用户的新表单,因此他们可以填写它。
   form = EmployeeForm()

# 从视图返回表单/错误。

请注意,这段代码是使用Django框架编写的Python代码,用于管理表单提交的持久性。

英文:

Since you're trying to persist the form submission across sessions, you can persist this information in the database or may also consider storing this info in redis. Here I'm assuming you'll be using the database.

You may keep track of this information in the existing Employee model, or if you know that you maybe have to extend this to other forms, you can create a separate model.

Here I'm using a separate a model that keep tracks of this information (if a row exists, it indicates that the form is already filled)

class EmployeeFormSubmission(models.Model):
    employee = models.OneToOneField(User, on_delete=models.CASCADE)

If you want to keep track of multiple forms, you can add another fields like form_name.

Finally, you can check if the current_employee already has submitted the form like this, and handle what you really want to do, depending on your business logic (I've indicated that in the code comments)

if EmployeeFormSubmission.objects.filter(employee=request.user).exists():
   # You can display an error here, or redirect in the view for 
   # editing the information.
else:
   # This is a new form for the user, so they can fill this in.
   form = EmployeeForm()

 # return the form/error from the view.

huangapple
  • 本文由 发表于 2023年2月27日 19:38:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75579998.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定