【问题标题】:Flask Admin validate unique_with errorsFlask 管理员验证 unique_with 错误
【发布时间】:2015-08-27 10:21:04
【问题描述】:

我有一个带有 unique_with 字段的烧瓶单引擎模型

class RedirectMixin(object):
name = db.StringField(max_length=1000, required=True, help_text="Used internally")
matching_type = db.IntField(
    help_text='`Equals` has higher priority. With concurrent `Start with` rules, longest `Url_from` wins',
    required=True, choices=MATCHING_TYPES)
add_unmatched_ending = db.BooleanField(
    help_text='Example: Starts with /a/ redirect to /b/. This will make /a/c/ redirect to /b/c/',
    default=False)
url_from = db.StringField(max_length=1000, required=True, unique_with='matching_type',
                          help_text='Case insensitive')
url_to = db.StringField(max_length=1000, required=True)

我想知道的是,为什么烧瓶管理员在管理员端填写表单时不验证是否违反本规范(unique_with 即),以及如果烧瓶管理员不是为它构建的,还如何进行验证.提前致谢

【问题讨论】:

    标签: python flask mongoengine flask-admin flask-mongoengine


    【解决方案1】:

    这种类型的验证需要与数据库交互,而 flask-admin 验证器可能无法提供。我为自己创建了一个自定义验证器,如下所示:

    class Unique(object):
    def __init__(self, with_=None, message=None):
        self.message = message
        self.with_ = with_
    
    def __call__(self, form, field):
        query, with_msg = {}, ''
        if self.with_:
            query[self.with_] = form[self.with_].data
            with_msg = 'with "%s"' % self.with_
        query[field.name] = field.data
        if form._obj:
            query['id__ne'] = form._obj.id
        matched_entries = form.model_class.objects(**query)
        if matched_entries:
            if self.message is None:
                self.message = field.gettext('Duplicate exists. Value Should be unique ' + with_msg)
            raise ValueError(self.message)
    is_unique = Unique
    

    然后在我的模型中我像这样使用它:

    from balut.lib.forms.validators import is_unique 
    
    class RedirectMixin(object):
        name = db.StringField(max_length=1000, required=True, help_text="Used internally")
        matching_type = db.IntField(
            help_text='`Equals` has higher priority. With concurrent `Start with` rules, longest `Url_from` wins',
            required=True, choices=MATCHING_TYPES)
        add_unmatched_ending = db.BooleanField(
            help_text='Example: Starts with /a/ redirect to /b/. This will make /a/c/ redirect to /b/c/',
            default=False)
        url_from = db.StringField(max_length=1000, required=True, unique_with='matching_type',
                                  help_text='Case insensitive')
        url_to = db.StringField(max_length=1000, required=True)
        form_args = dict(url_from={'validators': [is_unique(with_='matching_type', message=None)]})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-30
      • 1970-01-01
      • 1970-01-01
      • 2011-07-03
      • 1970-01-01
      • 2013-08-12
      • 1970-01-01
      • 2022-07-19
      相关资源
      最近更新 更多