获取名为“security_hash”的 HiddenInput 字段的错误
它在 documentation 中说如果我在我的模板中使用 {{ form }} 这些值将自动创建
但我没有使用模板,而只是使用带有 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 请求从中启动的任何上下文,并将它们包含在请求中以通过安全验证。
