DateTimeObject not being accepted by Django Model (that expects it) - python

In my models.py I have the following model:
from django.contrib.auth.models import User
class Notification(models.Model):
recipient = models.OneToOneField(User)
timestamp = models.DateTimeField()
In views.py, I try to create an instance of this model via Notification.objects.create(recipient = self.request.user, timestamp=timestamp) where self.request.user is an instance of User, and timestamp equals [datetime.datetime(2015, 10, 19, 16, 3, 2, 356585, tzinfo=<UTC>)]. Yet for these values, when the objects.create command is run, I get an error: Type error: expected string or buffer.
The line number happens to be the objects.create command. I suspect my datetime object is misconfigured. The whole trace is as follows:
Internal Server Error: /
Traceback (most recent call last):
File "/home/hassan/.virtualenvs/redditpk/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/home/hassan/.virtualenvs/redditpk/local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/home/hassan/.virtualenvs/redditpk/local/lib/python2.7/site-packages/django/views/generic/base.py", line 86, in dispatch
return handler(request, *args, **kwargs)
File "/home/hassan/.virtualenvs/redditpk/local/lib/python2.7/site-packages/django/views/generic/list.py", line 139, in get
context = self.get_context_data(object_list=self.object_list)
File "/home/hassan/Desktop/unconnectedredditpk/links/views.py", line 135, in get_context_data
Unseennotification.objects.create(recipient=self.request.user,timestamp=timestamp)
File "/home/hassan/.virtualenvs/redditpk/local/lib/python2.7/site-packages/django/db/models/manager.py", line 149, in create
return self.get_query_set().create(**kwargs)
File "/home/hassan/.virtualenvs/redditpk/local/lib/python2.7/site-packages/django/db/models/query.py", line 402, in create
obj.save(force_insert=True, using=self.db)
File "/home/hassan/.virtualenvs/redditpk/local/lib/python2.7/site-packages/django/db/models/base.py", line 546, in save
force_update=force_update, update_fields=update_fields)
File "/home/hassan/.virtualenvs/redditpk/local/lib/python2.7/site-packages/django/db/models/base.py", line 650, in save_base
result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "/home/hassan/.virtualenvs/redditpk/local/lib/python2.7/site-packages/django/db/models/manager.py", line 215, in _insert
return insert_query(self.model, objs, fields, **kwargs)
File "/home/hassan/.virtualenvs/redditpk/local/lib/python2.7/site-packages/django/db/models/query.py", line 1661, in insert_query
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/hassan/.virtualenvs/redditpk/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 936, in execute_sql
for sql, params in self.as_sql():
File "/home/hassan/.virtualenvs/redditpk/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 894, in as_sql
for obj in self.query.objs
File "/home/hassan/.virtualenvs/redditpk/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 304, in get_db_prep_save
prepared=False)
File "/home/hassan/.virtualenvs/redditpk/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 835, in get_db_prep_value
value = self.get_prep_value(value)
File "/home/hassan/.virtualenvs/redditpk/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 820, in get_prep_value
value = self.to_python(value)
File "/home/hassan/.virtualenvs/redditpk/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 788, in to_python
parsed = parse_datetime(value)
File "/home/hassan/.virtualenvs/redditpk/local/lib/python2.7/site-packages/django/utils/dateparse.py", line 67, in parse_datetime
match = datetime_re.match(value)
TypeError: expected string or buffer
Stumped about what to do here! I'm using Django 1.5 and Python 2.7.

Timestamp appears to be a list with one datetime in it. It should be a datetime, for example timestamp[0]. It could also be a correctly-formatted string - that's the code path the exception you're seeing comes from, but it fails because the value passed in is a list rather than a string.

Related

How fix this error : exchangelib.errors.InvalidTypeError: 'tzinfo' <UTC> must be of type <class 'exchangelib.ewsdatetime.EWSTimeZone'>

In my Django project, I have bump the Exchangelib version (3.2.1 to 4.9.0) and now an error occurs.
Traceback :
File "/home/.../workspace/my_project/exchange_manager/models.py", line 297, in create_event
event = self.create(*args, **kwargs)
File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/query.py", line 453, in create
obj.save(force_insert=True, using=self.db)
File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/base.py", line 726, in save
self.save_base(using=using, force_insert=force_insert,
File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/base.py", line 763, in save_base
updated = self._save_table(
File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/base.py", line 868, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/base.py", line 906, in _do_insert
return manager._insert(
File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/query.py", line 1270, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1409, in execute_sql
for sql, params in self.as_sql():
File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1352, in as_sql
value_rows = [
File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1353, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1353, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1294, in prepare_value
value = field.get_db_prep_save(value, connection=self.connection)
File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 842, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False)
File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 1428, in get_db_prep_value
return connection.ops.adapt_datetimefield_value(value)
File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/backends/sqlite3/operations.py", line 247, in adapt_datetimefield_value
value = timezone.make_naive(value, self.connection.timezone)
File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/utils/timezone.py", line 256, in make_naive
return value.astimezone(timezone).replace(tzinfo=None)
File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/exchangelib/ewsdatetime.py", line 128, in astimezone
t = super().astimezone(tz=tz).replace(tzinfo=tz)
File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/pytz/__init__.py", line 228, in fromutc
return super(utc.__class__, self).fromutc(dt)
File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/exchangelib/ewsdatetime.py", line 93, in __new__
raise InvalidTypeError("tzinfo", tzinfo, EWSTimeZone)
exchangelib.errors.InvalidTypeError: 'tzinfo' <UTC> must be of type <class 'exchangelib.ewsdatetime.EWSTimeZone'>
Before the call of the create method, I use this code to transform timestamp to EWSDateTime instance.
LOCAL_TZ = pytz.timezone('Europe/Paris')
def timestamp_to_ews_datetime(timestamp):
"""
Transform timestamp to EWSDateTime instance
:param timestamp:
:return:
"""
temp_datetime = datetime.datetime.fromtimestamp(timestamp / 1000.0)
temp_datetime = pytz.utc.localize(temp_datetime, is_dst=None).astimezone(LOCAL_TZ)
return EWSDateTime.from_datetime(temp_datetime)
I have edit the LOCAL_TZ value but it does not works :
LOCAL_TZ = EWSTimeZone('Europe/Paris')
I don't now if the problem is in this code.
Thwas was answered in https://github.com/ecederstrand/exchangelib/issues/1140#issuecomment-1308814613:
When you're trying to save an EWSDateTime to the database, the sqlite3 package is localizing datetime values to UTC and then removing the timezone info. EWSDateTime instances does not allow removing timezone info.
When you set the value on a Django model field, you should use a plain datetime object. The easiest way to convert from EWSDateTime to datetime is probably:
>>> from exchangelib import EWSDateTime, EWSTimeZone
>>> from datetime import datetime
>>> d = EWSDateTime(2013, 2, 1, tzinfo=EWSTimeZone.localzone())
>>> datetime(*d.timetuple()[:6], tzinfo=d.tzinfo)
datetime.datetime(2013, 1, 2, 0, 0, tzinfo=EWSTimeZone(key='Europe/Copenhagen'))

Date filters fail in django

I have a function:
def update_coins_table():
# Check if the currency has been updated in the last hour
up_to_date_currency = Currency.objects.filter(
currency_value_in_dollars_date=
[datetime.now(), timedelta(hours=1)]).order_by('-currency_value_in_dollars_date')[:len(coins_ids)]
if up_to_date_currency.exists():
# Return if it is
return
if not do_greeting():
print("Gecko crypto board not reachable. Db setup")
return
crypto_coins_prices = cg.get_price(ids=coins_ids_str, vs_currencies='usd')
datetime_now = datetime.now()
for coin_key in crypto_coins_prices:
coin = Currency(
currency_name=coin_key,
currency_value_in_dollars=crypto_coins_prices[coin_key]['usd'],
currency_value_in_dollars_date=datetime_now)
coin.save()
and get the following error on executing filter(),
up_to_date_currency = Currency.objects.filter(
currency_value_in_dollars_date=
[datetime.now(), timedelta(hours=1)]).order_by('-currency_value_in_dollars_date')[:len(coins_ids)]
Error message:
Internal Server Error: /get_currency/
Traceback (most recent call last):
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\projects\crypto-currency-board\crypto\manage_crypto_currency\views.py", line 21, in get_latest_currency
update_coins_table()
File "C:\projects\crypto-currency-board\crypto\manage_crypto_currency\get_coins_scheduler.py", line 38, in update_coins_table
up_to_date_currency = Currency.objects.filter(
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\query.py", line 942, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\query.py", line 962, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, *args, **kwargs)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\query.py", line 969, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\sql\query.py", line 1358, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\sql\query.py", line 1319, in build_filter
condition = self.build_lookup(lookups, col, value)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\sql\query.py", line 1165, in build_lookup
lookup = lookup_class(lhs, rhs)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\lookups.py", line 24, in __init__
self.rhs = self.get_prep_lookup()
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\lookups.py", line 76, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1357, in get_prep_value
value = super().get_prep_value(value)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1217, in get_prep_value
return self.to_python(value)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1318, in to_python
parsed = parse_datetime(value)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\utils\dateparse.py", line 107, in parse_datetime
match = datetime_re.match(value)
TypeError: expected string or bytes-like object
[22/Nov/2020 20:27:44] "GET /get_currency/ HTTP/1.1" 500 142548
The model of 'Currency' is:
class Currency(models.Model):
currency_name = models.CharField(max_length=100)
currency_value_in_dollars = models.FloatField()
currency_value_in_dollars_date = models.DateTimeField()
def __str__(self):
return self.currency_name
Why can't I filter by 'currency_value_in_dollars_date'? check if the currency value has been updated within the last hour.
You can not simply uses a list of two values to filter. If you for example want to retrieve all elements in between you can work with a __range lookup [Django-doc]:
from django.utils.timezone import now
current_time = now()
up_to_date_currency = Currency.objects.filter(
currency_value_in_dollars_date__range=(
current_time-timedelta(hours=1),
current_time
)
).order_by('-currency_value_in_dollars_date')[:len(coins_ids)]
This will thus retrieve all Currency objects between an hour ago and now.
If by
check if the currency value has been updated within the last hour
you mean you want to filter all rows up to 1 hour ago, then replace
currency_value_in_dollars_date=
[datetime.now(), timedelta(hours=1)]
with (notice __gte)
currency_value_in_dollars_date__gte=datetime.now() - timedelta(hours=1)
If you want to filter by array, then you'd have to either use JSONField to match value, or use __in to execute SQL in. Otherwise, you can't filter by array, so what you did is basically invalid.
Depending on your settings, you should probably use timezone.now() from django instead of datetime.

djongo.sql2mongo.SQLDecodeError: FAILED SQL: Error in django while filtering Data

I am trying to filter my product list with price less than filter but getting error. I guess the error is I am unable to pass parameters correctly.
any help would be appreciated.
if you require anymore details, please ask.
Note: it does not works even if I pass the query on filter body static.
thanks in advance.
my method:
def getfilter(request, format=None):
kwargs = {
'{0}__{1}'.format('price', 'lt'): Decimal('1000.00'),
# '{0}__{1}'.format('name', 'endswith'): 'Z'
}
products = Product.objects.all().filter(**kwargs)
serializer = ProductSerializer1(products, many=True)
return Response(serializer.data)
Error I Receive:
Traceback (most recent call last):
File "/home/sunil/.local/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 806, in parse
return handler(self, statement)
File "/home/sunil/.local/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 934, in _select
self._query = SelectQuery(self.db, self.connection_properties, sm, self._params)
File "/home/sunil/.local/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 113, in __init__
super().__init__(*args)
File "/home/sunil/.local/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 74, in __init__
self.parse()
File "/home/sunil/.local/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 153, in parse
raise SQLDecodeError
djongo.sql2mongo.SQLDecodeError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/sunil/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/sunil/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/sunil/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/sunil/.local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/sunil/.local/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/home/sunil/.local/lib/python3.6/site-packages/rest_framework/views.py", line 495, in dispatch
response = self.handle_exception(exc)
File "/home/sunil/.local/lib/python3.6/site-packages/rest_framework/views.py", line 455, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/sunil/.local/lib/python3.6/site-packages/rest_framework/views.py", line 492, in dispatch
response = handler(request, *args, **kwargs)
File "/home/sunil/.local/lib/python3.6/site-packages/rest_framework/decorators.py", line 55, in handler
return func(*args, **kwargs)
File "/home/sunil/Projects/python/loginBazaar/products/prodView.py", line 219, in getfilter
return Response(serializer.data)
File "/home/sunil/.local/lib/python3.6/site-packages/rest_framework/serializers.py", line 768, in data
ret = super(ListSerializer, self).data
File "/home/sunil/.local/lib/python3.6/site-packages/rest_framework/serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "/home/sunil/.local/lib/python3.6/site-packages/rest_framework/serializers.py", line 686, in to_representation
self.child.to_representation(item) for item in iterable
File "/home/sunil/.local/lib/python3.6/site-packages/django/db/models/query.py", line 274, in __iter__
self._fetch_all()
File "/home/sunil/.local/lib/python3.6/site-packages/django/db/models/query.py", line 1242, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/home/sunil/.local/lib/python3.6/site-packages/django/db/models/query.py", line 55, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "/home/sunil/.local/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1100, in execute_sql
cursor.execute(sql, params)
File "/home/sunil/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 99, in execute
return super().execute(sql, params)
File "/home/sunil/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 67, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/sunil/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/sunil/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/home/sunil/.local/lib/python3.6/site-packages/djongo/cursor.py", line 53, in execute
params)
File "/home/sunil/.local/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 743, in __init__
self.parse()
File "/home/sunil/.local/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 826, in parse
raise exe from e
djongo.sql2mongo.SQLDecodeError: FAILED SQL: SELECT "products_product"."id", "products_product"."name", "products_product"."vendorId", "products_product"."quantity", "products_product"."shopCode", "products_product"."discountPercent", "products_product"."discountPrice", "products_product"."price", "products_product"."dummyPrice", "products_product"."margin", "products_product"."description", "products_product"."is_verified", "products_product"."category", "products_product"."subCategory", "products_product"."images", "products_product"."sizeChart", "products_product"."attributes", "products_product"."buyCount", "products_product"."thumbnail", "products_product"."productCode", "products_product"."atts" FROM "products_product" WHERE "products_product"."price" < %(0)s ORDER BY "products_product"."productCode" ASC
Version: 1.2.32
It seems like the conversion from Decimal to string failed:
'{0}__{1}'.format('price', 'lt'): Decimal('1000.00'),
and corresponding SQL:
< %(0)s
I guess one of this possible troubles:
your model field price type is incorrect for this conversion
your decimal value have two zero numbers after decimal point - try to
remove the last one

Django REST Framework UniqueTogetherValidator

Problem Description:
The DRF UniqueTogetherValidator is displaying some odd behaviour.
For example:
models.py
class MyModel1(models.Model):
field1 = models.IntegerField()
field2 = models.ForeignKey('MyModel2', on_delete...)
class MyModel2(models.Model):
field3 = models.IntegerField()
serializer.py
from rest_framework.validators import UniqueTogetherValidator
class MyModel1Seriealizer(serializers.ModelSerializer):
class Meta:
model = MyModel1
validators = [
UniqueTogetherValidator(
queryset=MyModel1.objects.all(),
fields=('field1', 'field2_id')
)
]
When the condition is violated by field1 only, it reports back a good 400 response with a message in non_field_errors, but when the violated field is field2 (or its _id), the server gives back a response code 500 (meaning Django caught it at the database/ORM level).
The actual use-case is here on my GitHub.
Full traceback
Internal Server Error: /parts/10/
Traceback (most recent call last):
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 383, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: part_management_part.class_code_id, part_management_part.number
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/rest_framework/viewsets.py", line 116, in view
return self.dispatch(request, *args, **kwargs)
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/rest_framework/views.py", line 495, in dispatch
response = self.handle_exception(exc)
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/rest_framework/views.py", line 455, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/rest_framework/views.py", line 492, in dispatch
response = handler(request, *args, **kwargs)
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/rest_framework/mixins.py", line 84, in partial_update
return self.update(request, *args, **kwargs)
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/rest_framework/mixins.py", line 70, in update
self.perform_update(serializer)
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/rest_framework/mixins.py", line 80, in perform_update
serializer.save()
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/rest_framework/serializers.py", line 209, in save
self.instance = self.update(self.instance, validated_data)
File "/home/anani/PycharmProjects/part_management_backend/part_management/serializers.py", line 55, in update
instance.save()
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/django/db/models/base.py", line 741, in save
force_update=force_update, update_fields=update_fields)
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/django/db/models/base.py", line 779, in save_base
force_update, using, update_fields,
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/django/db/models/base.py", line 851, in _save_table
forced_update)
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/django/db/models/base.py", line 900, in _do_update
return filtered._update(values) > 0
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/django/db/models/query.py", line 760, in _update
return query.get_compiler(self.db).execute_sql(CURSOR)
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1429, in execute_sql
cursor = super().execute_sql(result_type)
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1100, in execute_sql
cursor.execute(sql, params)
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 99, in execute
return super().execute(sql, params)
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 67, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/home/anani/PycharmProjects/part_management_backend/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 383, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: part_management_part.class_code_id, part_management_part.number
[06/Jun/2019 23:37:04] "PATCH /parts/10/ HTTP/1.1" 500 22340
if field2_id is foreign key, you don't need to put field like that.
just put field2
from rest_framework.validators import UniqueTogetherValidator
class MyModel1Seriealizer(serializers.ModelSerializer):
class Meta:
model = MyModel1
validators = [
UniqueTogetherValidator(
queryset=MyModel1.objects.all(),
fields=('field1', 'field2')
)
]
and you can try post json data like this:
{
"field2": 1,
"field1": "test",
}

Django - Celery ValueError: Related model u'user.User' cannot be resolved

When I am executing celery task it is giving me:
ValueError: Related model u'user.User' cannot be resolved
The stacktrace is
Traceback (most recent call last):
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/celery/app/trace.py", line 375, in trace_task
R = retval = fun(*args, **kwargs)
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/celery/app/trace.py", line 632, in __protected_call__
return self.run(*args, **kwargs)
File "/Users/prince/work/magneto/set/facebook_pages/tasks.py", line 23, in analyze_page
connected_facebook_page = get_connected_facebook_page(connected_facebook_page_id)
File "/Users/prince/work/magneto/set/facebook_pages/utils.py", line 49, in get_connected_facebook_page
return ConnectedUserPage.objects.get(id=connected_facebook_page_id)
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/query.py", line 374, in get
num = len(clone)
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/query.py", line 232, in __len__
self._fetch_all()
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/query.py", line 1118, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/query.py", line 53, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch)
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 876, in execute_sql
sql, params = self.as_sql()
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 428, in as_sql
extra_select, order_by, group_by = self.pre_sql_setup()
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 46, in pre_sql_setup
self.setup_query()
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 37, in setup_query
self.select, self.klass_info, self.annotation_col_map = self.get_select()
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 194, in get_select
for c in self.get_default_columns():
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 569, in get_default_columns
column = field.get_col(alias)
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/fields/related.py", line 1008, in get_col
return super(ForeignKey, self).get_col(alias, output_field or self.target_field)
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/fields/related.py", line 909, in target_field
return self.foreign_related_fields[0]
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/fields/related.py", line 653, in foreign_related_fields
return tuple(rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field)
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/fields/related.py", line 640, in related_fields
self._related_fields = self.resolve_related_fields()
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/fields/related.py", line 625, in resolve_related_fields
raise ValueError('Related model %r cannot be resolved' % self.remote_field.model)
ValueError: Related model u'user.User' cannot be resolved
Here ConnectedUserPage is a model with schema:
class ConnectedUserPage(TimeStampedModel):
user = models.ForeignKey('user.User', on_delete=models.PROTECT)
page = models.ForeignKey(FacebookPage, on_delete=models.PROTECT)
page_details = jsonb.JSONField()
My versions are :
celery==4.1.1
django-celery-beat==1.1.1
django-celery-results==1.0.1
Django==1.11.13
In case I directly import User model from user app I am getting stuck in circular imports.
Any help would be appreciated, stuck in this loop for a quite while now.
Where's User defined? Is this Django's own user model? If that's the case you can use User model directly:
from django.contrib.auth import get_user_model
User = get_user_model()
class ConnectedUserPage(TimeStampedModel):
user = models.ForeignKey(User, unique=True)
or you can also do
from django.conf import settings
class ConnectedUserPage(TimeStampedModel):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
If it is your own supplied User model, are you sure user is in INSTALLED_APPS?

Categories