首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何正确地向Django的用户模型添加权限?

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

Stack Overflow用户
提问于 2017-11-23 04:34:50
回答 3查看 5.1K关注 0票数 1

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

在我的users应用程序的users文件中添加:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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
]

错误:

代码语言:javascript
复制
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.

问题:如何修复此错误?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-11-24 03:53:12

最后,我从文档中找到了解决方案。

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

代码语言:javascript
复制
python manage.py makemigrations --empty users

用户-应用程序名称

2)命令创建需要放置下一段代码的0001_initial.py文件:

代码语言:javascript
复制
# -*- 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),
    ]
票数 2
EN

Stack Overflow用户

发布于 2017-11-23 04:46:02

请尝试在init.py文件的顶部添加以下代码:

代码语言:javascript
复制
import django
django.setup()
票数 0
EN

Stack Overflow用户

发布于 2017-11-23 06:05:34

init.py中的所有代码复制到一个名为signals.py的新创建文件中,并将__init__.py更改为:

代码语言:javascript
复制
default_app_config = 'user.apps.UserConfig'

signals.py

代码语言:javascript
复制
from django.db.models.signals import pre_migrate
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import AuthConfig
from django.contrib.auth.models import Permission
from django.conf import settings
from django.dispatch import receiver


@receiver(pre_migrate, sender=AuthConfig)
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)

然后在user/apps.py中:

代码语言:javascript
复制
from django.apps import AppConfig


class UserConfig(AppConfig):
    name = 'user'
    verbose_name = 'User'

    def ready(self):
        import user.signals

您的错误是足球,因为__init__.py将在models.py中调用用户,但是用户模型将在__init__.py运行后注册,因此您需要在用户模型准备好时调用您的信号。

您希望添加一些与用户相关的perms,因此:

代码语言:javascript
复制
class MyUser(User):

    class Meta:
        permissions = (
            ("view_user", "view_user"),
            ("change_user_password", "change_user_password"),
        )

在settings.py中

代码语言:javascript
复制
AUTH_USER_MODEL = "user.MyUser"
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47447624

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档