名为“security_hash”的 HiddenInput 字段出现错误
它在documentation中说如果我在模板中使用 {{ form }},这些值就会自动创建
但我没有使用模板,而只是使用带有 POST 数据的 comments/post/端点,如下所示:
如何在没有此额外 View 作为 POST 值传递的情况下获取 security_hash 值?
编辑:我想是否可以并且建议将 {{ form.security_hash }} 值从模板/ View 传递到幕后的表单,以便避免此错误。
Edit2:为了澄清,有问题的 security_hash 字段是 shown here in code security_hash 值看起来像是从“initial_security_hash”函数生成的,该函数使用 content_type、object_pk
和 timestamp
字段在第 73 行生成哈希,该函数是在第 69 行调用。
因此,我也更加困惑为什么当我传入 content_type、object_pk
和 timestamp
字段时我的输入不被接受
最佳答案
发生这种情况是因为安全哈希是从实例化的 CommentSecurityForm
生成的。然后,安全哈希值作为隐藏字段包含在内,并通过 POST 请求传回,此时对其进行验证。
即使您将 content_type
、object_pk
和 timestamp
字段传递给请求,也没关系,因为您需要在提交 POST 请求之前具有 security_hash
值。
查看此处的文档 - https://github.com/django/django-contrib-comments/blob/master/django_comments/forms.py#L62
我猜您没有使用提供的 CommentSecurityForm
,它会自动包含安全验证字段。
如果这个假设是正确的,您应该实例化表单,例如
my_form = CommentSecurityForm(users.MyUser)
security_dict = my_form.generate_security_data()
然后,此 security_dict
包含以下键 - content_type
、object_pk
、timestamp
、security_hash
。然后,您需要将这些值传递到您发起 POST 请求的任何上下文,并将它们包含在请求中以通过安全验证。
关于python - Django 注释 security_hash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34349034/