【问题标题】:How to do a global validation in list editable django admin site如何在列表可编辑的 django 管理站点中进行全局验证
【发布时间】:2015-07-20 01:57:21
【问题描述】:

我正在尝试在 Django 管理站点的列表视图(使用可编辑)中对整数字段(序列)实现交换功能。我的代码:

models.py

class SortedMonitorables(models.Model):


    sequence = models.PositiveSmallIntegerField()
    monitorable_id = models.CharField(max_length=80, primary_key=True)

    def __unicode__(self):
        return u'{}-{}'.format(
             self.sequence, self.monitorable_id)

    class Meta(object):
        ordering = ['sequence']

forms.py

class SortedMonitorablesAdminForm(ModelForm):


    class Meta:
        model = SortedMonitorables

    def clean_sequence(self):
        """Manually sequence validation."""
        try:
            sequence = self.cleaned_data['sequence']
            monitorable_id = self.instance.monitorable_id
            records = SortedMonitorables.objects.filter(sequence=sequence).\
                exclude(monitorable_id=monitorable_id).count()
            if records >= 1:
                raise ValidationError(
                    'Sequence {} is already defined'.format(sequence))
        except ValidationError as e:
            raise ValidationError(e)
        except Exception:
            raise ValidationError('Fatal error checking sequence')
        else:
            return sequence

admin.py

@admin.register(SortedMonitorables)
class SortedMonitorableAdmin(admin.ModelAdmin):

    form = SortedMonitorablesAdminForm

    list_display = ('monitorable_id', 'sequence')
    list_display_links = ('monitorable_id',)
    list_editable = ('sequence',)
    search_fields = ['monitorable_id']
    list_per_page = 10

    def get_readonly_fields(self, request, obj=None):
        """Make some fields readonly on edition."""
        if obj:
            return self.readonly_fields + ('monitorable_id',)
        return self.readonly_fields

    def get_changelist_form(self, request, **kwargs):
        """Setting form to use in formset."""
        return SortedMonitorablesAdminForm

在管理网站我有这样的东西:

monitorable_id 序列 '啊' | 1 | 'bb' | 2 | '抄送' | 3 |

在该列表中,我可以直接修改序列,并且我为序列字段定义的验证(唯一值)在编辑页面和列表页面中都可以正常工作。当用户想要交换列表页面中的序列值时,我的问题出现了,即:用户想要同时更改“aa”和“bb”的序列,得到类似于:

monitorable_id 序列 '啊' | 2 | 'bb' | 1 | '抄送' | 3 |

当这种情况发生时,用户会收到一个错误,因为唯一序列验证检测到这两个数字已经被另一个可监控的定义/使用。在 Django 使用 SortedMonitorablesAdminForm 验证列表中的每一行之前,我想使该列表中的所有序列值都可编辑(来自表单集)。我怎样才能得到这些值?

提前致谢。

【问题讨论】:

    标签: python django django-admin


    【解决方案1】:

    一位同事向我推荐了一个可以满足我需求的应用程序,因此您可以找到它here!。使用该应用程序,我不需要验证交换功能,因为在模板中您一次只能更新一行。

    【讨论】:

      猜你喜欢
      • 2012-09-11
      • 2016-09-18
      • 2015-05-24
      • 1970-01-01
      • 1970-01-01
      • 2018-10-02
      • 2019-04-15
      • 2020-06-18
      • 1970-01-01
      相关资源
      最近更新 更多