ValueError: Cannot query "": Must be "Group" instance. Django
Добавил пользователя в django с правами на просмотр групп и шкафчиков. После этого вышел с админки и решил зайти под этим пользователем, дабы посмотреть, как будет выглядеть. Сразу же, после авторизации вылетела такая ошибка:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/
Django Version: 5.0.1
Python Version: 3.11.4
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'backend',
'userapp']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
^^^^^^^^^^^^^^^^^^^^^
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\contrib\admin\sites.py", line 259, in wrapper
return self.admin_view(view, cacheable)(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\utils\decorators.py", line 188, in _view_wrapper
result = _process_exception(request, e)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\utils\decorators.py", line 186, in _view_wrapper
response = view_func(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\views\decorators\cache.py", line 80, in _view_wrapper
response = view_func(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\contrib\admin\sites.py", line 240, in inner
return view(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\contrib\admin\sites.py", line 553, in index
app_list = self.get_app_list(request)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\contrib\admin\sites.py", line 537, in get_app_list
app_dict = self._build_app_dict(request, app_label)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\contrib\admin\sites.py", line 479, in _build_app_dict
has_module_perms = model_admin.has_module_permission(request)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\contrib\admin\options.py", line 636, in has_module_permission
return request.user.has_module_perms(self.opts.app_label)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\contrib\auth\models.py", line 331, in has_module_perms
return _user_has_module_perms(self, app_label)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\contrib\auth\models.py", line 235, in _user_has_module_perms
if backend.has_module_perms(user, app_label):
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\contrib\auth\backends.py", line 117, in has_module_perms
for perm in self.get_all_permissions(user_obj)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\contrib\auth\backends.py", line 105, in get_all_permissions
user_obj._perm_cache = super().get_all_permissions(user_obj)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\contrib\auth\backends.py", line 24, in get_all_permissions
*self.get_group_permissions(user_obj, obj=obj),
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\contrib\auth\backends.py", line 99, in get_group_permissions
return self._get_permissions(user_obj, obj, "group")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\contrib\auth\backends.py", line 80, in _get_permissions
perms = getattr(self, "_get_%s_permissions" % from_name)(user_obj)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\contrib\auth\backends.py", line 64, in _get_group_permissions
return Permission.objects.filter(**{user_groups_query: user_obj})
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\db\models\manager.py", line 87, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\db\models\query.py", line 1476, in filter
return self._filter_or_exclude(False, args, kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\db\models\query.py", line 1494, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, args, kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\db\models\query.py", line 1501, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\db\models\sql\query.py", line 1602, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\db\models\sql\query.py", line 1634, in _add_q
child_clause, needed_inner = self.build_filter(
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\db\models\sql\query.py", line 1521, in build_filter
self.check_related_objects(join_info.final_field, value, join_info.opts)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\db\models\sql\query.py", line 1335, in check_related_objects
self.check_query_object_type(value, opts, field)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Programs\OSPanel\domains\API\venv\Lib\site-packages\django\db\models\sql\query.py", line 1312, in check_query_object_type
raise ValueError(
^
Exception Type: ValueError at /admin/
Exception Value: Cannot query "": Must be "Group" instance.
Скорее всего это связано с тем, что я дополнял группы доп. полями. Мой admin.py:
from django.contrib import admin
# Register your backend here.
from userapp.models import User, WardrobeEvent, CardRental, Wardrobe, Section, MyGroup, GroupAdmin, WardrobeForm
from django.contrib.auth.models import Group
from django.contrib.auth.admin import GroupAdmin as BaseGroupAdmin
admin.site.site_header = "Администраторская панель"
class GroupInline(admin.StackedInline):
model = MyGroup
can_delete = False
verbose_name_plural = "Уровень доступа и описание"
class GroupInlineAdd(BaseGroupAdmin):
inlines = (GroupInline,)
# admin.site.register(User)
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
list_display = ("username", "email", "groups", "last_login")
admin.site.unregister(Group)
admin.site.register(WardrobeEvent)
admin.site.register(CardRental)
@admin.register(Wardrobe)
class WardrobeAdmin(admin.ModelAdmin):
form = WardrobeForm
admin.site.register(Section)
admin.site.register(Group, GroupInlineAdd)
admin.site.register(GroupAdmin)
Мой models.py:
import random
import string
from django.db import models
from django import forms
from django.contrib.auth.models import AbstractUser, Group
from backend.models import AccessLevel, Card
from django.core.validators import RegexValidator
from django.contrib.admin.widgets import AdminTextInputWidget
from django.contrib.auth.hashers import make_password
# Create your backend here.
class MyGroup(models.Model):
group = models.OneToOneField(to=Group, on_delete=models.CASCADE, null=False, primary_key=True)
access_level = models.ForeignKey(to=AccessLevel, on_delete=models.CASCADE)
description = models.CharField(max_length=150, blank=True)
def __str__(self):
return self.group.name
class Meta:
db_table = "Group"
verbose_name = "Группа"
verbose_name_plural = "Группы"
class User(AbstractUser):
groups = models.ForeignKey(to=MyGroup, on_delete=models.CASCADE, null=True, default=2)
def save(self, *args, **kwargs):
if not self.pk:
self.password = make_password(self.password)
super().save(*args, **kwargs)
def __str__(self):
return self.email
class Meta:
db_table = "User"
verbose_name = "Пользователь"
verbose_name_plural = "Пользователи"
ordering = ("username", "email")
class GroupAdmin(models.Model):
group = models.OneToOneField(Group, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, default=0)
class Meta:
db_table = "GroupAdmin"
verbose_name = "Администратор группы"
verbose_name_plural = "Администраторы групп"
class Section(models.Model):
required_access_level = models.ForeignKey(to=AccessLevel, on_delete=models.CASCADE)
admin = models.ForeignKey(to=User, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
description = models.TextField(blank=True)
def __str__(self):
return self.name
class Meta:
db_table = "Section"
verbose_name = "Секция"
verbose_name_plural = "Секции"
class Wardrobe(models.Model):
section = models.ForeignKey(to=Section, on_delete=models.CASCADE)
address = models.GenericIPAddressField()
mac = models.CharField(max_length=17, unique=True, default="00:00:00:00:00:00")
secret = models.CharField(max_length=256, default="a" * 64, editable=False)
def save(self, **kwargs):
if not self.pk:
salt = random.choices(string.ascii_lowercase, k=16)
self.secret = make_password(self.secret, salt)
super().save(**kwargs)
def __str__(self):
return self.address
class Meta:
db_table = "Wardrobe"
verbose_name = "Шкафчик"
verbose_name_plural = "Шкафчики"
class WardrobeForm(forms.ModelForm):
address = forms.GenericIPAddressField(widget=AdminTextInputWidget(attrs={'placeholder': 'Введите IP-адрес'}))
mac = forms.CharField(max_length=17, validators=[RegexValidator(regex=r'^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$',
message="Введите MAC-адрес в формате XX:XX:XX:XX:XX:XX")],
widget=AdminTextInputWidget(attrs={'placeholder': 'Введите MAC-адрес'}))
class Meta:
model = Wardrobe
fields = "__all__"
Группы в базе данных:
Моя доп. таблица group: