删除Django中的旧权限

Mar*_*116 5 django

在我的Django站点中,有一些权限条目链接到我已删除的应用程序。例如,我具有链接到“仪表板”和“ Jet”应用程序的权限条目。如何删除它们?

all*_*aps 16

首先,创建一个空的迁移文件:

python manage.py makemigrations --empty yourappname
Run Code Online (Sandbox Code Playgroud)

更改迁移(这是一个示例,根据您的需要进行调整):

# -*- coding: utf-8 -*-
from __future__ import unicode_literals    
from django.db import migrations    


def add_permissions(apps, schema_editor):
    pass


def remove_permissions(apps, schema_editor):
    """Reverse the above additions of permissions."""
    ContentType = apps.get_model('contenttypes.ContentType')
    Permission = apps.get_model('auth.Permission')
    content_type = ContentType.objects.get(
        model='somemodel',
        app_label='yourappname',
    )
    # This cascades to Group
    Permission.objects.filter(
        content_type=content_type,
        codename__in=('add_somemodel', 'change_somemodel', 'delete_somemodel'),
    ).delete()

class Migration(migrations.Migration):
    dependencies = [
        ('yourappname', '0001_initial'),
    ]
    operations = [
        migrations.RunPython(remove_permissions, add_permissions),
    ]
Run Code Online (Sandbox Code Playgroud)


小智 7

权限在幕后具有内容类型的外键,因此删除不再存在的模型的内容类型也将删除这些模型的权限。

幸运的是,Django 还提供了一个manage.py删除旧内容类型的命令:remove_stale_contenttypes. 运行该命令将列出不再存在的内容类型以及将被删除的相关对象(包括权限),允许您查看更改并批准它们。

$ manage.py remove_stale_contenttypes
Some content types in your database are stale and can be deleted.
Any objects that depend on these content types will also be deleted.
The content types and dependent objects that would be deleted are:

    - Content type for stale_app.removed_model
    - 4 auth.Permission object(s)

This list doesn't include any cascade deletions to data outside of Django's
models (uncommon).

Are you sure you want to delete these content types?
If you're unsure, answer 'no'.
Type 'yes' to continue, or 'no' to cancel:
Run Code Online (Sandbox Code Playgroud)

  • 此管理命令还采用可选参数“--include-stale-apps”:“删除过时的内容类型,包括已从 INSTALLED_APPS 中删除的先前安装的应用程序中的内容类型。” (引自命令帮助文本)。 (2认同)