python - Django 最佳实践 : How to clean and render a form

标签 python django

情况:我有一个用于搜索的表单,我在结果页面上返回相同的表单,供用户过滤他们的结果。为了摆脱垃圾输入,我实现了一个 clean_xxx 方法。

不幸的是,即使清理了表单,结果页面上仍会返回带有垃圾输入的表单。我怎样才能得到干净的数据来显示?

这里有一些想法:

  1. 在clean_xxx方法中,设置self.data.xxx = cleaned_xxx值
  2. 使用 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/

相关文章:

mysql - 在django中采样mysql结果

python - 关于使用column.isnull()&column.str.len() > n进行df条件选择的问题

python - OSX 上的 Pyaudio 类型错误

django - RabbitMQ Pika 和 Django channel websocket

python - 从另一个模型 Django 添加字段

python - nginx 和 uwsgi 服务器中 uwsgi 模块的区别

c++ - scons:对象、源代码、可执行文件,都在单独的目录中

python - 将列表变成集合,然后再返回,会导致 Python 出现问题吗?

python - 使用完整路径时 pyenv virtualenv 激活不起作用

Django db_index=True 不创建索引,但类元索引是