自定义验证 Django 管理员未知字段



我正在尝试对管理面板中的imageField进行自定义验证,但是出现以下错误。事件模型类中有 nog 字段,名称banner_image,但是当我将字段 = ('banner_image',) 更改为其他内容时,我得到的不是为 EventBanner 指定的"为事件指定"。我发现大多数用于进行自定义验证的解决方案都适用于旧版本的 Django。

django.core.exceptions.FieldError: Unknown field(s) (banner_image) specified for Event. Check fields/fieldsets/exclude attributes of class EventAdmin.

应用 admin.py:

class BannerImageForm(forms.ModelForm):
   class Meta:
       model = EventBanner
       fields = ['banner_image',]
   def clean_banner_image(self):
       banner_image = self.cleaned_data['banner_image']
       if not banner_image:
           raise forms.ValidationError("No image!")
       else:
           w, h = get_image_dimensions(banner_image)
           if w != 1200:
               raise forms.ValidationError("The image is %i pixel wide. It's supposed to be 1200px" % w)
           if h != 200:
               raise forms.ValidationError("The image is %i pixel high. It's supposed to be 200px" % h)
       return banner_image
class EventAdmin(admin.ModelAdmin):
    form = BannerImageForm
    list_display = ('event_name', 'event_start_date')
    formfield_overrides={
    models.TextField:{'widget':Textarea(attrs={'rows':15, 'cols':80})}
    }
admin.site.register(Event, EventAdmin)

应用 models.py:

class EventBanner(models.Model):
    event = models.OneToOneField(Event, unique=True)
    banner_image = models.ImageField(upload_to=get_image_path, blank=True, null=True)
    def clean(self):
        validate_only_one_instance(self)

追踪:

Environment:

Request Method: GET
Request URL: http://localhost:8000/admin/events/event/1/change/
Django Version: 1.10.4
Python Version: 3.5.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'organizations.apps.OrganizationsConfig',
 'news.apps.NewsConfig',
 'events.apps.EventsConfig',
 'bootstrap3',
 'django_forms_bootstrap',
 'registration']
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',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware']

Traceback:
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/contrib/admin/options.py" in get_form
  642.             return modelform_factory(self.model, **defaults)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/forms/models.py" in modelform_factory
  548.     return type(form)(class_name, (form,), form_class_attrs)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/forms/models.py" in __new__
  257.                 raise FieldError(message)
During handling of the above exception (Unknown field(s) (banner_image) specified for Event), another exception occurred:
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
  39.             response = get_response(request)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/contrib/admin/options.py" in wrapper
  544.                 return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view
  149.                     response = view_func(request, *args, **kwargs)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  57.         response = view_func(request, *args, **kwargs)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/contrib/admin/sites.py" in inner
  211.             return view(request, *args, **kwargs)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/contrib/admin/options.py" in change_view
  1512.         return self.changeform_view(request, object_id, form_url, extra_context)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapper
  67.             return bound_func(*args, **kwargs)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view
  149.                     response = view_func(request, *args, **kwargs)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/utils/decorators.py" in bound_func
  63.                 return func.__get__(self, type(self))(*args2, **kwargs2)
File "/usr/lib/python3.5/contextlib.py" in inner
  30.                 return func(*args, **kwds)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/contrib/admin/options.py" in changeform_view
  1438.         ModelForm = self.get_form(request, obj)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/contrib/admin/options.py" in get_form
  608.             fields = flatten_fieldsets(self.get_fieldsets(request, obj))
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/contrib/admin/options.py" in get_fieldsets
  298.         return [(None, {'fields': self.get_fields(request, obj)})]
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/contrib/admin/options.py" in get_fields
  597.         form = self.get_form(request, obj, fields=None)
File "/home/dave/Projecten/Web/Django/venv/lib/python3.5/site-packages/django/contrib/admin/options.py" in get_form
  646.                 % (e, self.__class__.__name__)
Exception Type: FieldError at /admin/events/event/1/change/
Exception Value: Unknown field(s) (banner_image) specified for Event. Check fields/fieldsets/exclude attributes of class EventAdmin.

EventAdmin的表单必须使用Event模型。您收到错误BannerImageForm因为窗体使用EventBanner模型。

创建一个EventBannerAdmin,并让你的代码使用它。然后,您可以将其更改为内联,并将内联包含在EventAdmin中。

相关内容

  • 没有找到相关文章