本文介绍了Django管理员错误ValidationError:['ManagementForm数据丢失或已被篡改']由于有条件的内联使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义的 User 模型( AbstractUser )和一个 Stock 模型.假设有多个用户角色经理,供应商等.经理可以查看其他经理的详细信息和供应商详细信息.

I have a custom User model(AbstractUser) and a Stock model. Assume there's multiple user roles manager, supplier etc. The manager can be able to view other manager's details and supplier details.

User 模型具有有条件的内联,如果用户角色等于供应商 .(这里的角色是 PositiveSmallIntegerField ,其中包含选项和 SUPPLIER = 2 )

The User model got a conditional inline which shows the stocks of each supplier if the user role is equalled to supplier.(Here role is a PositiveSmallIntegerField with choices and SUPPLIER = 2)

class SupplierStockInline(admin.StackedInline):
    """ Inline to show stocks of a supplier """

    model = Stock
    extra = 0


@admin.register(User)
class UserAdmin(UserAdmin):
    """ User """

    fieldsets = [
        (None, {'fields': ('username', 'password')}),
        ('Personal info', {'fields': (
            'first_name',
            'last_name',
            'email',
            ... some custom fields...
        )}),
        ('Permissions', {'fields': (
            'is_active',
            'is_staff',
            'is_superuser',
            'role',
            'groups',
            'user_permissions',
        )}),
        ('Important dates', {'fields': ('last_login', 'date_joined')})
    ]

    list_display = [...]
    search_fields = [...]

    # --- the source of the problem ---

    inlines = []

    def get_inlines(self, request, obj):
        """ Show inlines, stocks of supplier """
        try:
            if obj.role == SUPPLIER:
                return [SupplierStockInline]
        except:
            pass
        return []
    # --- ---- -----

在我尝试将新用户的角色更改为供应商之前,此方法正常工作.

This works just fine till I tried to change the role of a new user to supplier.

ValidationError: ['ManagementForm data is missing or has been tampered with']

问题是由于覆盖 get_inlines() 方法.当我注释掉 get_inlines()时,它可以正常工作,并且仅在角色 supplier 中才发生.我试图解决这个问题,但无法提出解决方案.

The issue is due to that overridden get_inlines() method. When I comment out the get_inlines() it works fine and this is only happening for the role supplier. I tried to tackle this but unable to come up with a solution.

希望能为解决该问题提供指导.

Hoping for guidance to solve the issue, thanks in advance.

推荐答案

经过数小时的研究,终于找到了解决方案,尽管我无法确切解释为什么会发生这种情况(可能与没有相关的库存实例,以及当更换为角色供应商后突然与库存实例相关).

After hours of research finally found a solution, although I cannot exactly explain why it happening (might be related to not having related stock instances and suddenly having relations to stock instances when changed into role supplier).

无论如何,不​​是覆盖 get_inlines()方法,而是覆盖 change_view() ,并使用条件方法可以解决问题,

Anyway, instead of overriding the get_inlines() method, overriding change_view()and using a conditional approach can solve the problem,

class UserAdmin(admin.ModelAdmin):
    ...
    inlines = []

    def change_view(self, request, object_id, form_url='', extra_context=None):
        self.inlines = []
    
        try:
            obj = self.model.objects.get(pk=object_id)
        except self.model.DoesNotExist:
            pass
        else:
            if obj.role == SUPPLIER:
                self.inlines = [SupplierStockInline,]
        return super(UserAdmin, self).change_view(request, object_id, form_url, extra_context)

这篇关于Django管理员错误ValidationError:['ManagementForm数据丢失或已被篡改']由于有条件的内联使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 20:06