@NyxDeveloper

ValueError invalid literal for int()?

Есть класс, сохраняющий в кэш формы запроса, для его создания используется текущий пользователь. Выбрасывает ошибку при создании объекта класса, хотя данные корректные и отладчик показывает что все передается верно, однако ошибка все же есть. В чем может быть причина?

Создание объекта:
cache, created = ContactCache.objects.get_or_create(user_id=request.user.id)


Traceback:
Environment:

Request Method: GET
Request URL: 127.0.0.1:8000/contacts

Django Version: 2.2
Python Version: 3.8.5
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'adminlte3',
'spurl',
'jquery',
'dashboard',
'contacts']
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 "/home/nyx/.local/lib/python3.8/site-packages/django/db/models/query.py" in get_or_create
538. return self.get(**kwargs), False

File "/home/nyx/.local/lib/python3.8/site-packages/django/db/models/query.py" in get
406. raise self.model.DoesNotExist(

During handling of the above exception (ContactCache matching query does not exist.), another exception occurred:

File "/home/nyx/.local/lib/python3.8/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)

File "/home/nyx/.local/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)

File "/home/nyx/.local/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/nyx/.local/lib/python3.8/site-packages/django/views/generic/base.py" in view
71. return self.dispatch(request, *args, **kwargs)

File "/home/nyx/.local/lib/python3.8/site-packages/django/views/generic/base.py" in dispatch
97. return handler(request, *args, **kwargs)

File "/home/nyx/projects/TestApp3/contacts/views.py" in get
39. cache, created = ContactCache.objects.get_or_create(user_id=request.user.id)

File "/home/nyx/.local/lib/python3.8/site-packages/django/db/models/manager.py" in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/home/nyx/.local/lib/python3.8/site-packages/django/db/models/query.py" in get_or_create
541. return self._create_object_from_params(kwargs, params)

File "/home/nyx/.local/lib/python3.8/site-packages/django/db/models/query.py" in _create_object_from_params
575. obj = self.create(**params)

File "/home/nyx/.local/lib/python3.8/site-packages/django/db/models/query.py" in create
422. obj.save(force_insert=True, using=self.db)

File "/home/nyx/.local/lib/python3.8/site-packages/django/db/models/base.py" in save
740. self.save_base(using=using, force_insert=force_insert,

File "/home/nyx/.local/lib/python3.8/site-packages/django/db/models/base.py" in save_base
777. updated = self._save_table(

File "/home/nyx/.local/lib/python3.8/site-packages/django/db/models/base.py" in _save_table
870. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)

File "/home/nyx/.local/lib/python3.8/site-packages/django/db/models/base.py" in _do_insert
907. return manager._insert([self], fields=fields, return_id=update_pk,

File "/home/nyx/.local/lib/python3.8/site-packages/django/db/models/manager.py" in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/home/nyx/.local/lib/python3.8/site-packages/django/db/models/query.py" in _insert
1186. return query.get_compiler(using=using).execute_sql(return_id)

File "/home/nyx/.local/lib/python3.8/site-packages/django/db/models/sql/compiler.py" in execute_sql
1331. for sql, params in self.as_sql():

File "/home/nyx/.local/lib/python3.8/site-packages/django/db/models/sql/compiler.py" in as_sql
1273. value_rows = [

File "/home/nyx/.local/lib/python3.8/site-packages/django/db/models/sql/compiler.py" in
1274. [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]

File "/home/nyx/.local/lib/python3.8/site-packages/django/db/models/sql/compiler.py" in
1274. [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]

File "/home/nyx/.local/lib/python3.8/site-packages/django/db/models/sql/compiler.py" in prepare_value
1215. value = field.get_db_prep_save(value, connection=self.connection)

File "/home/nyx/.local/lib/python3.8/site-packages/django/db/models/fields/__init__.py" in get_db_prep_save
789. return self.get_db_prep_value(value, connection=connection, prepared=False)

File "/home/nyx/.local/lib/python3.8/site-packages/django/db/models/fields/__init__.py" in get_db_prep_value
784. value = self.get_prep_value(value)

File "/home/nyx/.local/lib/python3.8/site-packages/django/db/models/fields/__init__.py" in get_prep_value
1807. return int(value)

Exception Type: ValueError at /contacts/
Exception Value: invalid literal for int() with base 10: ''

Класс кэша:
class ContactCache(models.Model):
    user_id = models.IntegerField(blank=True, unique=True)

    KEY = models.IntegerField(default='', null=True, blank=True)
    info = models.CharField(max_length=100, default='', blank=True)
    type = models.CharField(max_length=100, default='', blank=True)
    subject = models.CharField(max_length=100, default='', blank=True)


Возможно ли, что в request.user.id лежит не int?
  • Вопрос задан
  • 34 просмотра
Решения вопроса 1
@galaxy
KEY = models.IntegerField(default=''
default должен типу соответствовать. Если пустое надо - None
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
от 150 000 до 180 000 ₽
Appboxo Алматы
от 830 000 до 1 250 000 ₸
Verme Москва
от 120 000 ₽
27 янв. 2021, в 04:19
2500 руб./за проект
27 янв. 2021, в 00:37
11111 руб./за проект
26 янв. 2021, в 23:30
3000 руб./за проект