情况:我有一个用于搜索的表单,我在结果页面上返回相同的表单,供用户过滤他们的结果。为了摆脱垃圾输入,我实现了一个 clean_xxx 方法。
不幸的是,即使清理了表单,结果页面上仍会返回带有垃圾输入的表单。我怎样才能得到干净的数据来显示?
这里有一些想法:
- 在clean_xxx方法中,设置self.data.xxx = cleaned_xxx值
- 使用 cleaned_data 重新初始化一个新表单。
表单.py:
SearchForm:
def clean_q(self):
q = self.cleaned_data.get('q').strip()
# Remove Garbage Input
sanitized_keywords = re.split('[^a-zA-Z0-9_ ]', q)
q = "".join(sanitized_keywords).strip()
#TODO: Fix
self.data['q'] = q
return q
View .py
search_form = SearchForm(params, user=request.user)
if search_form.is_valid():
# Build the Query from the form
# Retrieve The Results
else:
# For errors, no results will be displayed
_log.error('Search: Form is not valid. Error = %s' %search_form.errors)
response = {
'search_form': search_form...
}
感谢您的帮助。
最佳答案
无论您从 clean_xxx 方法返回什么,都会显示什么。所以,例如:
表单.py:
class SearchForm(forms.Form):
def clean_q(self):
return "spam and eggs"
在上面的示例中,该字段将显示“垃圾邮件和鸡蛋”。
如果它没有这样做,那么问题很可能出在您的方法的验证逻辑上。
关于python - Django 最佳实践 : How to clean and render a form,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10096425/