gpt4 book ai didi

Django/表格 : How can i validate initial data against received data (if match)?

转载 作者:行者123 更新时间:2023-12-02 05:07:57 25 4
gpt4 key购买 nike

假设我正在创建一个表单,并且我正在通过绑定(bind)传递一些隐藏的值,这些值不能更改。我的问题是如何测试恶意用户是否更改了此隐藏值?我不确定表单中的绑定(bind)数据和初始值之间的区别究竟是什么。

在 Django 的 forms.py 中有一个名为 changed_data 的属性,但我不知道是否可以提供帮助。

演示代码:

表单.py

class ConfirmForm(forms.Form):
client_id = forms.CharField(widget=forms.HiddenInput())
identifier = forms.CharField(widget=forms.HiddenInput())

def clean(self):
# Maybe here the validation process of cliend_id and identifier like:
clean_client_id = self.cleaned_data.get('client_id')
clean_identifier = self.cleaned_data.get('identifier')
if last_client_id == clean_client_id and
last_identifier == clean_identifier:
return self.cleaned_data
else:
raise forms.ValidationError("False data.")

views.py

def form_confirm_handler(request):
if request.method == 'POST':
form = ConfirmForm(request.POST)
if form.is_valid():
#Do something...
return redirect('home:index')

#The following values are not fixed. Are generated variables!
bound_data = {'client_id':'123456','identifier':'wuiy5895'}
form = ConfirmForm(bound_data)
return render(request, 'client/theform.html', {'form':form})

html 模板

<form action="{% url 'client:confirm' %}" method="post">
<p>Do you really want to proceed?</p>
{% csrf_token %}
{{ form.client_id }}
{{ form.identifier }}
<button id="submit" type="submit" name="submit" class="btn" value="accept">Accept</button>
<button id="cancel" type="submit" name="cancel" class="btn btn-primary" value="cancel">Cancel</button>
</form>

提前致谢!

最佳答案

我找到了 4 个(简单的)可能的解决方案来解决这个问题。

Django 最有效的解决方案是这样的:

class TheFormName():
client_id = forms.CharField(show_hidden_initial=True, widget=forms.HiddenInput())
identifier = forms.CharField(show_hidden_initial=True, widget=forms.HiddenInput())

def clean(self):
if self.has_changed():
raise forms.ValidationError('Fields are not valid.')

return self.cleaned_data

第二种解决方案是使用 changed_data 查看发生了什么变化:

def clean(self):
for field_name in self.changed_data:
# loop through the fields which have changed
print "field {} has changed. New value {}".format(field_name, cleaned_data['field_name']

对于我的情况,翻译成这样,但与 has_changed() 方法完全相同:

def clean(self):
if len(self.changed_data) > 0:
raise forms.ValidationError('Fields are not valid.')

return self.cleaned_data

另一个看起来更像是 hack 的解决方案是:

self.cleaned_data['cliend_id'] == self.instance.cliend_id
self.cleaned_data['identifier'] == self.instance.identifier

最终的解决方案有点复杂,是在 clean() 方法内(和 View 外)使用 session 。来自 Django Docs 的示例:

from django.contrib.sessions.backends.db import SessionStore
import datetime
s = SessionStore()
s['last_login'] = datetime.datetime(2005, 8, 20, 13, 35, 10)
s.save()
s.session_key
>>> '2b1189a188b44ad18c35e113ac6ceead'

s = SessionStore(session_key='2b1189a188b44ad18c35e113ac6ceead')
s['last_login']

这篇文章也很有用 In Django 1.4, do Form.has_changed() and Form.changed_data, which are undocumented, work as expected?由@LarsVegas 提供

关于Django/表格 : How can i validate initial data against received data (if match)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15977034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com