Django:如何清理表单字段并避免代码重复 [英] Django: how to cleanup form fields and avoid code duplication

查看:27
本文介绍了Django:如何清理表单字段并避免代码重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常需要在使用之前过滤一些表单数据(保存到数据库等).假设我想在许多表单中的大多数文本字段中去除空格并将重复的空格替换为单个空格.使用 clean_ 方法不难做到这一点:

Quite often I need to filter some form data before using it (saving to database etc.) Let's say I want to strip whitespaces and replace repeating whitespaces with a single one in most of the text fields, in many forms. It's not difficult to do this using clean_<fieldname> methods:

# Simplified model with two text fields
class MyModel(models.Model):
    title = models.CharField()
    description = models.CharField()

# Model-based form
class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel

    def clean_title(self):
        title = self.cleaned_data['title']
        return re.sub(r's{2,}', ' ', title.strip())

    def clean_description(self):
        description = self.cleaned_data['description']
        return re.sub(r's{2,}', ' ', description.strip())

它完全符合我的需要,并且有一个很好的副作用,我喜欢:如果用户只输入空格,则该字段将被视为空,因此无效(如果需要),我什至不必抛出一个 ValidationError.

It does exactly what I need, and has a nice side effect which I like: if user enters only whitespaces, the field will be considered empty and therefore invalid (if it is required) and I don't even have to throw a ValidationError.

这里明显的问题是代码重复.即使我会为此创建一些函数,比如 my_text_filter,我也必须为我所有表单中的每个文本字段调用它:

The obvious problem here is code duplication. Even if I'll create some function for that, say my_text_filter, I'll have to call it for every text field in all my forms:

from myproject.filters import my_text_filter

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel

    def clean_title(self):
        return my_text_filter(self.cleaned_data['title'])

    def clean_description(self):
        return my_text_filter(self.cleaned_data['description'])

问题:在 Django 中是否有任何标准和简单的方法(如果重要的话我使用 1.2 版)来做到这一点(例如,通过添加属性 validators = {'title': my_text_filter, 'description': my_text_filter}MyModel),或者至少是一些或多或少的标准解决方法?我在文档中阅读了有关表单验证和验证器的内容,但在那里找不到我需要的内容.

The question: is there any standard and simple way in Django (I use version 1.2 if that matters) to do this (like, for example, by adding property validators = {'title': my_text_filter, 'description': my_text_filter} to MyModel), or at least some more or less standard workaround? I've read about form validation and validators in the documentation, but couldn't find what I need there.

推荐答案

据我所知,Django 没有任何本地解决方案来解决您的问题.我只能展示我如何为自己解决这个问题.我建议您为您的 ModelForm 使用 decorator.这里的工作代码(我也使用日志模块):

as i know Django don't have any native solutions to resolve you question. I can show only how i resolve this problem for myself. I advice you to use decorator for you ModelForm. Here the working code(also i use logging module):

#DECORATOR
def applyValidators(model_form):
    def apply(*args,**kwargs):
        try:
            if hasattr(model_form.Meta.model,"validators"):
                for field_name,fnc in model_form.Meta.model.validators.items():
                    setattr(model_form,"clean_%s" % field_name,fnc)
        except Exception,err:
            logging.error(str(err))
        return model_form(*args,**kwargs)
    return apply

#VALIDATORS
def validator(*args,**kwargs):
    return "SOMEVALUE"

#MODEL
class MyModel(models.Model):
    #Your fields
    .......
    .......
    .......

    #VALIDATE DICT
    validators = {"username":validator,"email":validator}    

#MODEL FORM
@applyValidators
class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
    .......
    .......
    .......

这篇关于Django:如何清理表单字段并避免代码重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆