python - 如何正确向Django的用户模型添加权限?

标签 python django python-2.7 django-users django-1.11

我正在尝试向 User 模型 (django.contrib.auth.models) 添加自定义权限。

到我的 users 应用程序的 __init__.py 文件中添加:

from django.db.models.signals import pre_migrate
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth import models as auth_models
from django.contrib.auth.models import Permission
from django.conf import settings
from django.dispatch import receiver


@receiver(pre_migrate, sender=auth_models)
def add_user_permissions(sender, **kwargs):
    content_type = ContentType.objects.get_for_model(settings.AUTH_USER_MODEL)
    Permission.objects.get_or_create(codename='view_user', name=' Can view users', content_type=content_type)
    Permission.objects.get_or_create(codename='change_user_password', name=' Can change user password', content_type=content_type)

settings.py:

INSTALLED_APPS = [
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.forms',
    'django_select2',  # "django-select2" application
    'custom_app',  # "custom_app" application
    'custom_app_2',  # "custom_app_2" application
    'modeltranslation',  # "django-modeltranslation" application
    'users', # "users" application
]

错误:

Traceback (most recent call last):
  File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper
    fn(*args, **kwargs)
  File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
    autoreload.raise_last_exception()
  File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception
    six.reraise(*_exception)
  File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper
    fn(*args, **kwargs)
  File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate
    app_config = AppConfig.create(entry)
  File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/apps/config.py", line 94, in create
    module = import_module(entry)
  File "/usr/local/Cellar/python/2.7.14/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Applications/Projects/web/dashboard.kase.kz/users/__init__.py", line 5, in <module>
    from django.contrib.contenttypes.models import ContentType
  File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/contrib/contenttypes/models.py", line 139, in <module>
    class ContentType(models.Model):
  File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/db/models/base.py", line 110, in __new__
    app_config = apps.get_containing_app_config(module)
  File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/apps/registry.py", line 247, in get_containing_app_config
    self.check_apps_ready()
  File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/apps/registry.py", line 125, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

问题:如何修复此错误?

最佳答案

最后我从 documentation 找到了解决方案.

1)您需要使用下一个命令创建空迁移:

python manage.py makemigrations --empty users

用户 - 应用程序的名称

2) 命令创建 0001_initial.py 文件,您需要在其中放置下一个代码:

# -*- coding: utf-8 -*-

from __future__ import unicode_literals
from django.db import migrations

def forwards_func(apps, schema_editor):
    User = apps.get_model('auth', 'User')
    Permission = apps.get_model('auth', 'Permission')
    ContentType = apps.get_model('contenttypes', 'ContentType')
    content_type = ContentType.objects.get_for_model(User)
    db_alias = schema_editor.connection.alias
    Permission.objects.using(db_alias).bulk_create([
        Permission(codename='view_user', name=' Can view users', content_type=content_type),
        Permission(codename='change_user_password', name=' Can change user password', content_type=content_type)
    ])


class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.RunPython(forwards_func),
    ]

关于python - 如何正确向Django的用户模型添加权限?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47447624/

相关文章:

python - 为什么 if else 速记不能与 break 一起使用 - Python

python - Scikit-learn 的 GridSearchCV 中的 Grid_scores_ 是什么意思

python - 如何为受身份验证保护的 REST API 编写 Django 单元测试?

javascript - 使用 Django 通过 AJAX URL 传递参数

python - Django 中的嵌套 GROUP BY : returning Objects

Python - 将 xml 中的特定行转换为小写并写回 - utf-8 问题

sql - Python中有 "template engine"来生成SQL吗?

python - seaborn : plotting graph from dataframe in loop not working as expected

python - 如何将字符串数据分类为整数?

python - python 中的类方法可以使用和不可以使用什么?