Home > OS >  RuntimeError: 'empty_form' is not used in polymorphic formsets, use 'empty_forms'
RuntimeError: 'empty_form' is not used in polymorphic formsets, use 'empty_forms'

Time:07-11

I am developing a django api project based on the django rest framework. I have 4 models:

class Module(models.Model):
    name = models.CharField(null=False, max_length=50, verbose_name='название')
    description = models.TextField(null=False, verbose_name='описание')
    image = models.ImageField(null=False, upload_to="image/module", verbose_name='картинка модуля')
    first_level = models.ForeignKey('plotbackend.Level', null=False, db_column='first_level_id', on_delete=models.PROTECT, related_name=' ', verbose_name='первый уровень')

    def __str__(self):
        return self.name

    class Meta:
        db_table = 'module'
        verbose_name = "модуль"
        verbose_name_plural = 'модули'


class Level(PolymorphicModel):
    name = models.CharField(null=True, blank=True, max_length=25, verbose_name="название")
    description = models.TextField(null=True, blank=True, verbose_name="описание")
    module = models.ForeignKey(Module, null=True, blank=True, verbose_name='модуль', db_column='module_id', on_delete=models.CASCADE, related_name='levels')
    next_level = models.ForeignKey('self', null=True, blank=True, verbose_name='следующий уровень', db_column='next_level_id', on_delete=models.SET_NULL)

    def __str__(self):
        return f'{self.name}'

    class Meta:
        db_table = 'level'
        verbose_name = "уровень"
        verbose_name_plural = 'уровни'


class Puzzle(Level):
    time = models.PositiveIntegerField(null=False)


class Test(Level):
    time = models.IntegerField(null=True, blank=True, verbose_name='время на прохождение теста')

    class Meta:
        db_table = 'test'
        verbose_name = "тест"
        verbose_name_plural = "тесты"

and Admin models:

from django.contrib import admin
from polymorphic.admin import StackedPolymorphicInline, PolymorphicInlineSupportMixin, PolymorphicChildModelAdmin, PolymorphicParentModelAdmin
from .models import *

# Register your models here.

@admin.register(Test)
class TestAdmin(PolymorphicChildModelAdmin):
    base_model = Test


@admin.register(Puzzle)
class PuzzleAdmin(PolymorphicChildModelAdmin):
    base_model = Puzzle


@admin.register(Level)
class LevelAdmin(PolymorphicParentModelAdmin):
    base_model = Level
    child_models = (Test, Puzzle, )


class LevelInline(StackedPolymorphicInline):
    class TestInline(StackedPolymorphicInline.Child):
        model = Test

    class PuzzleInline(StackedPolymorphicInline.Child):
        model = Puzzle

    model = Level
    child_inlines = (
        TestInline,
        PuzzleInline,
    )


@admin.register(Module)
class ModuleAdmin(admin.ModelAdmin, PolymorphicInlineSupportMixin):
    inlines = (LevelInline,)

PolymorphicModelAdmin works fine for me but StackedPolymorphicInline throws this exception. Traceback

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/admin/plotbackend/module/1/change/

Django Version: 4.0.5
Python Version: 3.9.7
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'plotbackend.apps.PlotbackendConfig',
 'rest_framework',
 'polymorphic']
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:\PyCharm Projects\plot\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "D:\PyCharm Projects\plot\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\PyCharm Projects\plot\lib\site-packages\django\contrib\admin\options.py", line 683, in wrapper
    return self.admin_site.admin_view(view)(*args, **kwargs)
  File "D:\PyCharm Projects\plot\lib\site-packages\django\utils\decorators.py", line 133, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "D:\PyCharm Projects\plot\lib\site-packages\django\views\decorators\cache.py", line 62, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "D:\PyCharm Projects\plot\lib\site-packages\django\contrib\admin\sites.py", line 242, in inner
    return view(request, *args, **kwargs)
  File "D:\PyCharm Projects\plot\lib\site-packages\django\contrib\admin\options.py", line 1888, in change_view
    return self.changeform_view(request, object_id, form_url, extra_context)
  File "D:\PyCharm Projects\plot\lib\site-packages\django\utils\decorators.py", line 46, in _wrapper
    return bound_method(*args, **kwargs)
  File "D:\PyCharm Projects\plot\lib\site-packages\django\utils\decorators.py", line 133, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "D:\PyCharm Projects\plot\lib\site-packages\django\contrib\admin\options.py", line 1745, in changeform_view
    return self._changeform_view(request, object_id, form_url, extra_context)
  File "D:\PyCharm Projects\plot\lib\site-packages\django\contrib\admin\options.py", line 1843, in _changeform_view
    media = media   inline_formset.media
  File "D:\PyCharm Projects\plot\lib\site-packages\django\contrib\admin\helpers.py", line 443, in media
    for fs in self:
  File "D:\PyCharm Projects\plot\lib\site-packages\django\contrib\admin\helpers.py", line 366, in __iter__
    self.formset.empty_form,
  File "D:\PyCharm Projects\plot\lib\site-packages\polymorphic\formsets\models.py", line 292, in empty_form
    raise RuntimeError(

Exception Type: RuntimeError at /admin/plotbackend/module/1/change/
Exception Value: 'empty_form' is not used in polymorphic formsets, use 'empty_forms' instead.

If I comment inlines field in ModuleAdmin project works without any exception. I tried to find a solution to the problem on the internet but found nothing. How to fix it?

CodePudding user response:

I solved the problem on my own.

I just changed ModuleAdmin from

@admin.register(Module)
class ModuleAdmin(admin.ModelAdmin, PolymorphicInlineSupportMixin):
    inlines = (LevelInline,)

to

@admin.register(Module)
class ModuleAdmin(PolymorphicInlineSupportMixin, admin.ModelAdmin):
    inlines = (LevelInline,)

that is, I just changed the order of inheritance

  • Related