在进行自定义模型验证工作后,Django管理验证无法正常工作

时间:2017-05-18 20:29:21

标签: django validation django-models

我有一个Django模型,可以将照片上传到用户的帐户。上传模型使用Django auth用户作为外键。我需要确保每个用户总共只能上传20张照片,并且我希望在模型级别执行此操作,因此即使管理员也无法上传更多内容。我在某种程度上工作,但它破坏了我的管理表单验证。如果我选择相关用户,一切都很顺利。它阻止我上传超过20张照片。但如果我不选择用户,它会给我一个RelatedObjectDoesNotExist错误。我在这里包含我的代码和回溯。帮助将不胜感激。

我的models.py

def photo_count(self):
    theModel = self.__class__
    refModel = theModel.objects.filter(user=self.user)
    picCount = refModel.count()
    if picCount ==20:
        print(picCount)
        raise ValidationError ("You have already uploaded 20 photos. Delete some to upload more.")


class StarPhotos(models.Model):

    user = models.ForeignKey(User, on_delete=models.CASCADE)
    PHOTO_CATEGORY = (
    ('HS', "Head Shot"),
    ('WP', "Western Party Wear"),
    ('IP', "Indian Party Wear"),
    ('SW', "Swim Wear"),
    ('CW', "Casual Wear"),
    )
    category = models.CharField(max_length=2, choices=PHOTO_CATEGORY, default='CW')
    # This FileField should preferaby be changed to ImageField with pillow installed.
    photos = models.FileField(max_length=200, upload_to='images/',)

    def __str__(self):
        return "Images for {0}".format(self.user)


    def clean(self):
        photo_count(self)


    class Meta:
        verbose_name_plural = "Star Photos"

回溯

Request Method: POST
Request URL: http://127.0.0.1:8000/admin/castar/starphotos/add/

Django Version: 1.11.1
Python Version: 3.6.1
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'castar.apps.CastarConfig']
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:

File "D:\websites\powah\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "D:\websites\powah\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "D:\websites\powah\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "D:\websites\powah\lib\site-packages\django\contrib\admin\options.py" in wrapper
  551.                 return self.admin_site.admin_view(view)(*args, **kwargs)

File "D:\websites\powah\lib\site-packages\django\utils\decorators.py" in _wrapped_view
  149.                     response = view_func(request, *args, **kwargs)

File "D:\websites\powah\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
  57.         response = view_func(request, *args, **kwargs)

File "D:\websites\powah\lib\site-packages\django\contrib\admin\sites.py" in inner
  224.             return view(request, *args, **kwargs)

File "D:\websites\powah\lib\site-packages\django\contrib\admin\options.py" in add_view
  1508.         return self.changeform_view(request, None, form_url, extra_context)

File "D:\websites\powah\lib\site-packages\django\utils\decorators.py" in _wrapper
  67.             return bound_func(*args, **kwargs)

File "D:\websites\powah\lib\site-packages\django\utils\decorators.py" in _wrapped_view
  149.                     response = view_func(request, *args, **kwargs)

File "D:\websites\powah\lib\site-packages\django\utils\decorators.py" in bound_func
  63.                 return func.__get__(self, type(self))(*args2, **kwargs2)

File "D:\websites\powah\lib\site-packages\django\contrib\admin\options.py" in changeform_view
  1408.             return self._changeform_view(request, object_id, form_url, extra_context)

File "D:\websites\powah\lib\site-packages\django\contrib\admin\options.py" in _changeform_view
  1440.             if form.is_valid():

File "D:\websites\powah\lib\site-packages\django\forms\forms.py" in is_valid
  183.         return self.is_bound and not self.errors

File "D:\websites\powah\lib\site-packages\django\forms\forms.py" in errors
  175.             self.full_clean()

File "D:\websites\powah\lib\site-packages\django\forms\forms.py" in full_clean
  386.         self._post_clean()

File "D:\websites\powah\lib\site-packages\django\forms\models.py" in _post_clean
  396.             self.instance.full_clean(exclude=exclude, validate_unique=False)

File "D:\websites\powah\lib\site-packages\django\db\models\base.py" in full_clean
  1233.             self.clean()

File "D:\websites\powah\src\castar\models.py" in clean
  75.         photo_count(self)

File "D:\websites\powah\src\castar\models.py" in photo_count
  49.     refModel = theModel.objects.filter(user=self.user)

File "D:\websites\powah\lib\site-packages\django\db\models\fields\related_descriptors.py" in __get__
  194.                 "%s has no %s." % (self.field.model.__name__, self.field.name)

Exception Type: RelatedObjectDoesNotExist at /admin/castar/starphotos/add/
Exception Value: StarPhotos has no user.

0 个答案:

没有答案