Django - TypeError: объект типа 'int' не имеет len () - PullRequest
0 голосов
/ 08 февраля 2020

У меня есть django модель Project, которая выглядит следующим образом:


class Project(models.Model):
    slug            = models.SlugField(null=True, blank=True, unique=True,default="")
    project_title   = models.CharField(null=True, blank=True, max_length=120)
    project_post    = models.TextField(null=True, blank=True)
    project_cat     = models.CharField(null=True, blank=True,max_length=20)
    project_thumb   = models.ImageField(upload_to=upload_image_path, null=True, blank=True)
    project_movie   = models.FileField(upload_to=upload_image_path, null=True, blank=True,default='False')
    project_views   = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True,related_name='project_views',default=0)
    project_likes   = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True,related_name='project_likes',default=0)
    project_date    = models.DateTimeField(null=True, blank=True, auto_now_add=True)

Когда я пытаюсь создать новый проект, я получаю эту ошибку:


Django Version: 3.0.3
Python Version: 3.8.1


Traceback (most recent call last):
  File "C:\Users\...\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\...\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\...\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\...\lib\site-packages\django\contrib\admin\options.py", line 607, in wrapper
    return self.admin_site.admin_view(view)(*args, **kwargs)
  File "C:\Users\...\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "C:\Users\...\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "C:\Users\...\lib\site-packages\django\contrib\admin\sites.py", line 231, in inner
    return view(request, *args, **kwargs)
  File "C:\Users\...\lib\site-packages\django\contrib\admin\options.py", line 1638, in add_view
    return self.changeform_view(request, None, form_url, extra_context)
  File "C:\Users\...\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
    return bound_method(*args, **kwargs)
  File "C:\Users\...\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "C:\Users\...\lib\site-packages\django\contrib\admin\options.py", line 1522, in changeform_view
    return self._changeform_view(request, object_id, form_url, extra_context)
  File "C:\Users\...\lib\site-packages\django\contrib\admin\options.py", line 1567, in _changeform_view
    change_message = self.construct_change_message(request, form, formsets, add)
  File "C:\Users\...\lib\site-packages\django\contrib\admin\options.py", line 1043, in construct_change_message
    return construct_change_message(form, formsets, add)
  File "C:\Users\...\lib\site-packages\django\contrib\admin\utils.py", line 495, in construct_change_message
    changed_data = form.changed_data
  File "C:\Users\...\lib\site-packages\django\utils\functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Users\...\lib\site-packages\django\forms\forms.py", line 451, in changed_data
    if field.has_changed(initial_value, data_value):
  File "C:\Users\...\lib\site-packages\django\forms\models.py", line 1354, in has_changed
    if len(initial) != len(data):

Exception Type: TypeError at /admin/webdata/project/add/
Exception Value: object of type 'int' has no len()

Спасибо

1 Ответ

0 голосов
/ 08 февраля 2020

Ваша проблема с установкой значения по умолчанию для отношения ManyToMany для project_views и project_likes. Поле ManyToMany ожидает некоторую форму набора запросов или списка (так как его много), но в вашем случае вы устанавливаете его 0 как int. Измените ваши 2 поля следующим образом (уведомление по умолчанию),

...
project_views   = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True,related_name='project_views',default=[0])
project_likes   = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True,related_name='project_likes',default=[0])
...

или, как рекомендует документация , вернуть значение из метода класса следующим образом:

....
def get_zero_user():
    """
    A list of pk's you want to set for your many to many
    """
    return [0]

project_views = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='project_views', default=get_zero_user())
project_likes = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='project_likes', default=get_zero_user())
...

Надеюсь, это поможет!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...