Organizations.OrganizationGroups не имеет ForeignKey для 'auth.User'

В моей установке администратора Django случайным образом появляется следующее исключение. OrganizationGroups не имеет внешнего ключа к auth.User. Это исключение также появляется в различных приложениях системы, и оно всегда organizations.OrganizationGroups has no ForeignKey to 'app.Model'

В настоящее время я выполняю:

  • Django Версия: 3.2.13
  • Python Версия: 3.9.2

Модель OrganizationGroups:

class OrganizationGroups(models.Model):
    id = models.BigAutoField(primary_key=True)
    organization = models.ForeignKey(
        Organization, models.DO_NOTHING, null=True, blank=True
    )
    group = models.ForeignKey(Group, models.CASCADE, blank=True, null=True)

    class Meta:
        db_table = 'organization_groups'
        unique_together = (('organization', 'group'),)

    def __str__(self) -> str:
        return self.organization.name

UserAdmin ModelAdmin:

UserForm ModelForm:

from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.forms.models import ModelForm

class UserForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(UserForm, self).__init__(*args, **kwargs)
        try:
            user: User = User.objects.get(id=self.instance.pk)
            if user == self.user:
                if self.user.is_superuser:
                    self.fields['is_superuser'].disabled = True
                self.fields['is_active'].disabled = True
                self.fields['groups'].disabled = True
                self.fields['user_permissions'].disabled = True
                self.fields['last_login'].disabled = True
                self.fields['date_joined'].disabled = True
        except User.DoesNotExist:
            pass

    def clean(self):
        for string, field in self.fields.items():
            if field.disabled is True:
                raise ValidationError(
                    'No puede realizar modificaciones a su propio usuario.',
                    'own_user_is_not_editable'
                )
        return super().clean()

Если вам нужна дополнительная информация, не стесняйтесь задать ее, и я отредактирую свой вопрос!

Я решил проблему. Проблема была вызвана тем, как я создавал OrganizationGroups inline, используя get_inlines в GroupAdmin (который является переопределением стандартного GroupAdmin). Раньше я использовал super().get_inlines(request, obj), и когда я переходил в другой модуль, модуль пытался воссоздать OrganizationGroups inline, а модуль не имел отношения к OrganizationGroups (потому что не должен был), и тогда он ломался. Теперь я создаю инлайн, создавая совершенно новый список без использования super().get_inlines(request, obj), и, по-видимому, это решило проблему.

OrganizationInline:

class OrganizationInline(StackedInline):
    model = Organization.groups.through
    autocomplete_fields = ('organization')
    extra = 0
    min_num = 0
    max_num = 1
    verbose_name = _('organización')
    verbose_name_plural = _('organizaciones')

Предыдущий get_inlines код:

def get_inlines(self, request, obj):
        inlines = super().get_inlines(request, obj)
        if request.user.is_superuser:
            inlines.clear()
            inlines.append(OrganizationInline)
        return inlines

Новый get_inlines код:

def get_inlines(self, request: HttpRequest, obj):
        if request.user.is_superuser:
            return [OrganizationInline]
        return []
Вернуться на верх