Related
Hello I'm newbie Python user.
I study now django queryset. but
query.pyi in _BaseQuerySet's method
def values(self, *fields: Union[str, Combinable], **expressions: Any) -> ValuesQuerySet[_T, Dict[str, Any]]: ...
I want to pass a parameter to that function, but the first code runs, but the second code does not.
here is error code
valuelist = ("col1", "col2")
comment = Comment.objects.annotate(col1=F("contents"), col2=F("comment_depth")).values(valuelist)
and showed up if above code run
Traceback (most recent call last):
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\rest_framework\viewsets.py", line 114, in view
return self.dispatch(request, *args, **kwargs)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\rest_framework\views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
raise exc
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\rest_framework\views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "D:\djangostudy\DjangoStudy\member\views.py", line 79, in memberlistrlist nt_depth")).values(valuelist)
comment = Comment.objects.annotate(col1=F("contents"), col2=F("commes\query.py", line 841, in valuesment_depth")).values(valuelist)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\django\db\models\query.py", line 836, in _valuesels\query.py", line 841, in values
clone = self._values(*fields, **expressions)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\django\db\models\query.py", line 836, in _values
clone.query.set_values(fields)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\django\db\models\sql\query.py", line 2172, in set_values
self.add_fields(field_names, True)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\django\db\models\sql\query.py", line 1863, in add_fields
join_info = self.setup_joins(name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m)
ttributeError: 'tuple' object has no attribute 'split'
14/Mar/2021 19:14:09] "GET /member/memberlist/ HTTP/1.1" 500 116044
not error code
comment = Comment.objects.annotate(col1=F("contents"), col2=F("comment_depth")).values("col1", "col2")
What should I do to get it running normally?
The error is in the .values(…) clause: you can not pass a tuple as parameter. You use iterable unpack to unpack the values of an iterable as individual parameters. This is done by putting an asterisk (*) in front:
Comment.objects.annotate(
col1=F('contents'),
col2=F('comment_depth')
).values(*valuelist)
That being said, often it is not a good idea to work with .values(…) [Django-doc] since it "erodes" the model layer.
TypeError: object of type 'JsonResponse' has no len() when return the json values.But print (dicts) and print( json.dumps(dicts)),it shows the values ,but when the return the JsonResponse(json.dumps(dicts), safe=False) shows an error like 'TypeError: object of type 'JsonResponse' has no len()',how to solve this problem.
Error
Internal Server Error: /api/v2/usernewslist/
Traceback (most recent call last):
File "C:\duklr\Duklr-web\venv\lib\site-
packages\django\core\handlers\exception.py", line 41, in inner
response = get_response(request)
File "C:\duklr\Duklr-web\venv\lib\site-
packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\duklr\Duklr-web\venv\lib\site-
packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\duklr\Duklr-web\venv\lib\site-
packages\django\views\decorators\csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "C:\duklr\Duklr-web\venv\lib\site-packages\rest_framework\viewsets.py",
line 116, in view
return self.dispatch(request, *args, **kwargs)
File "C:\duklr\Duklr-web\venv\lib\site-packages\rest_framework\views.py",
line 495, in dispatch
response = self.handle_exception(exc)
File "C:\duklr\Duklr-web\venv\lib\site-packages\rest_framework\views.py",
line 455, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\duklr\Duklr-web\venv\lib\site-packages\rest_framework\views.py",
line 492, in dispatch
response = handler(request, *args, **kwargs)
File "C:\duklr\Duklr-web\venv\lib\site-packages\rest_framework\mixins.py",
line 42, in list
page = self.paginate_queryset(queryset)
File "C:\duklr\Duklr-web\venv\lib\site-
packages\rest_framework\generics.py", line 173, in paginate_queryset
return self.paginator.paginate_queryset(queryset, self.request, view=self)
File "C:\duklr\Duklr-web\venv\lib\site-
packages\rest_framework\pagination.py", line 204, in paginate_queryset
self.page = paginator.page(page_number)
File "C:\duklr\Duklr-web\venv\lib\site-packages\django\core\paginator.py",
line 57, in page
number = self.validate_number(number)
File "C:\duklr\Duklr-web\venv\lib\site-packages\django\core\paginator.py",
line 46, in validate_number
if number > self.num_pages:
File "C:\duklr\Duklr-web\venv\lib\site-packages\django\utils\functional.py",
line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\duklr\Duklr-web\venv\lib\site-packages\django\core\paginator.py",
line 91, in num_pages
if self.count == 0 and not self.allow_empty_first_page:
File "C:\duklr\Duklr-web\venv\lib\site-
packages\django\utils\functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\duklr\Duklr-web\venv\lib\site-packages\django\core\paginator.py",
line 84, in count
return len(self.object_list)
TypeError: object of type 'JsonResponse' has no len()
[29/Feb/2020 14:10:22] "GET /api/v2/usernewslist/ HTTP/1.1" 500 20471
Views.py
class UserNewsListingListViewSet(MobileNewsListViewSet):
def get_queryset(self):
queryset = self.queryset.filter(publish=True)
queryset = queryset.exclude(news_summary='')
# Filter News Provider
if self.request.GET.get('user_id'):
queryset = queryset.filter(posted_by__id=self.request.GET.get('user_id'))
# Filter News Category
if self.request.GET.get('news_type'):
queryset = queryset.filter(news_category__slug=self.request.GET.get('news_type'))
dicts = []
for query in queryset[:6]:
id = query.id
newstitle = query.news_title
news_summary = query.news_summary
slug = query.slug
news_image = query.news_image
news_provider = query.news_provider
news_page_url = query.news_page_url
newsdate = query.news_datetime
likescount = query.likes_count
mobile_news_summary = query.mobile_news_summary
for cat in query.news_category.all():
news_category = cat.news_category
data = {
"id":id,
"newstitle":newstitle,
"news_categories":news_category,
"news_summary":news_summary,
"slug":slug,
"news_image":news_image,
"news_provider":{
"id":query.news_provider.id,
"news_providers": query.news_provider.news_provider,
"url":query.news_provider.url,
"region":query.news_provider.region,
"image":str(query.news_provider.image),
"descriptions":query.news_provider.description,
"followers":query.news_provider.followers,
"slug":query.news_provider.slug,
"created_time":query.news_provider.created_time,
"publish":query.news_provider.publish
},
"news_page_url":news_page_url,
"newsdate":newsdate,
"likescount":likescount,
"mobile_news_summary":mobile_news_summary
}
# dat=json.dumps(data)
dicts.append(data)
return JsonResponse(json.dumps(dicts), safe=False)
When return the dicts , it shows an error like,
Traceback (most recent call last):
File "C:\duklr\Duklr-web\venv\lib\site-
packages\django\core\handlers\exception.py", line 41, in inner
response = get_response(request)
File "C:\duklr\Duklr-web\venv\lib\site-
packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\duklr\Duklr-web\venv\lib\site-
packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\duklr\Duklr-web\venv\lib\site-
packages\django\views\decorators\csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "C:\duklr\Duklr-web\venv\lib\site-packages\rest_framework\viewsets.py",
line 116, in view
return self.dispatch(request, *args, **kwargs)
File "C:\duklr\Duklr-web\venv\lib\site-packages\rest_framework\views.py",
line 495, in dispatch
response = self.handle_exception(exc)
File "C:\duklr\Duklr-web\venv\lib\site-packages\rest_framework\views.py",
line 455, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\duklr\Duklr-web\venv\lib\site-packages\rest_framework\views.py",
line 492, in dispatch
response = handler(request, *args, **kwargs)
File "C:\duklr\Duklr-web\venv\lib\site-packages\rest_framework\mixins.py",
line 45, in list
return self.get_paginated_response(serializer.data)
File "C:\duklr\Duklr-web\venv\lib\site-
packages\rest_framework\serializers.py", line 768, in data
ret = super(ListSerializer, self).data
File "C:\duklr\Duklr-web\venv\lib\site-
packages\rest_framework\serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "C:\duklr\Duklr-web\venv\lib\site-
packages\rest_framework\serializers.py", line 686, in to_representation
self.child.to_representation(item) for item in iterable
File "C:\duklr\Duklr-web\venv\lib\site-
packages\rest_framework\serializers.py", line 530, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "C:\duklr\Duklr-web\venv\lib\site-packages\rest_framework\relations.py",
line 542, in to_representation
for value in iterable
File "C:\duklr\Duklr-web\venv\lib\site-packages\rest_framework\relations.py",
line 272, in to_representation
return value.pk
AttributeError: 'unicode' object has no attribute 'pk'
[02/Mar/2020 12:37:15] "GET /api/v2/usernewslist/ HTTP/1.1" 500 20224
when code changed
class UserNewsListingListViewSet(MobileNewsListViewSet):
def get_queryset(self):
queryset = self.queryset.filter(publish=True)
queryset = queryset.exclude(news_summary='')
# Filter News Provider
if self.request.GET.get('user_id'):
queryset = queryset.filter(posted_by__id=self.request.GET.get('user_id'))
# Filter News Category
if self.request.GET.get('news_type'):
queryset = queryset.filter(news_category__slug=self.request.GET.get('news_type'))
dicts = []
for query in queryset[:6]:
id = query.id
newstitle = query.news_title
news_summary = query.news_summary
slug = query.slug
news_image = query.news_image
news_provider = query.news_provider
news_page_url = query.news_page_url
newsdate = query.news_datetime
likescount = query.likes_count
mobile_news_summary = query.mobile_news_summary
for cat in query.news_category.all():
news_category = cat.id
data = {
"id":str(id),
"newstitle":str(newstitle),
"news_category":str(news_category),
"news_summary":str(news_summary),
"slug":str(slug),
"news_image":str(news_image),
"news_provider":{
"id":str(query.news_provider.id),
"news_providers": str(query.news_provider.news_provider),
"url":str(query.news_provider.url),
"region":str(query.news_provider.region),
"image":str(query.news_provider.image),
"descriptions":str(query.news_provider.description),
"followers":str(query.news_provider.followers),
"slug":str(query.news_provider.slug),
"created_time":str(query.news_provider.created_time),
"publish":str(query.news_provider.publish)
},
"news_page_url":str(news_page_url),
"newsdate":str(newsdate),
"likescount":str(likescount),
"mobile_news_summary":str(mobile_news_summary)
}
dat = json.dumps(data)
dicts.append(dat)
return dicts
It shows an error like this,
Traceback:
Traceback (most recent call last):
File "/home/test/.local/lib/python2.7/site-
packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/home/test/.local/lib/python2.7/site-
packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/test/.local/lib/python2.7/site-
packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args,
**callback_kwargs)
File "/home/test/.local/lib/python2.7/site-
packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/home/test/.local/lib/python2.7/site-
packages/rest_framework/viewsets.py", line 116, in view
return self.dispatch(request, *args, **kwargs)
File "/home/test/.local/lib/python2.7/site-
packages/rest_framework/views.py", line 495, in dispatch
response = self.handle_exception(exc)
File "/home/test/.local/lib/python2.7/site-
packages/rest_framework/views.py", line 455, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/test/.local/lib/python2.7/site-
packages/rest_framework/views.py", line 492, in dispatch
response = handler(request, *args, **kwargs)
File "/home/test/.local/lib/python2.7/site-
packages/rest_framework/mixins.py", line 45, in list
return self.get_paginated_response(serializer.data)
File "/home/test/.local/lib/python2.7/site-
packages/rest_framework/serializers.py", line 768, in data
ret = super(ListSerializer, self).data
file "/home/test/.local/lib/python2.7/site-
packages/rest_framework/serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "/home/test/.local/lib/python2.7/site-
packages/rest_framework/serializers.py", line 686, in
to_representation
self.child.to_representation(item) for item in iterable
File "/home/test/.local/lib/python2.7/site-
packages/rest_framework/serializers.py", line 517, in
to_representation
attribute = field.get_attribute(instance)
File "/home/test/.local/lib/python2.7/site-
packages/rest_framework/relations.py", line 536, in get_attribute
relationship = get_attribute(instance, self.source_attrs)
File "/home/test/.local/lib/python2.7/site-
packages/rest_framework/fields.py", line 101, in get_attribute
instance = getattr(instance, attr)
AttributeError: 'str' object has no attribute 'news_category'
First parameter for JsonResponse takes a dict. You are passing in json.dumps which will return a converted string corresponding to your dicts list. Use something like
JsonResponse({'data':dicts}, safe=False)
If your code's indent is not wrong, you have a logical error.In your second for loop for cat in query.news_category.all() change news_category variable, but it doesn't inserted anywhere .
I am integrating drf-yasq swagger for the first time, Sorry! if my question is silly. I read the doc from here https://drf-yasg.readthedocs.io/en/stable/readme.html and followed the instructions and end up with AttributeError: 'Response' object has no attribute 'label'. original code is from https://drf-yasg.readthedocs.io/en/stable/readme.html. please help me where I am lacking:
Terminal:
Internal Server Error: /swagger/
Traceback (most recent call last):
File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site-
packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site-
packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site-
packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site-
packages/django/views/decorators/csrf.py", line 54, in wrapped_view
r . eturn view_func(*args, **kwargs)
File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site-
packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site-
packages/rest_framework/views.py", line 497, in dispatch
response = self.handle_exception(exc)
File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site-
packages/rest_framework/views.py", line 457, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site-
packages/rest_framework/views.py", line 468, in raise_uncaught_exception
raise exc
File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site-
packages/rest_framework/views.py", line 494, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site-
packages/drf_yasg/views.py", line 94, in get
schema = generator.get_schema(request, self.public)
File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site-
packages/drf_yasg/generators.py", line 254, in get_schema
paths, prefix = self.get_paths(endpoints, components, request, public)
File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site-
packages/drf_yasg/generators.py", line 412, in get_paths
operation = self.get_operation(view, path, prefix, method, components, request)
File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site-
packages/drf_yasg/generators.py", line 454, in get_operation
operation = view_inspector.get_operation(operation_keys)
File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site-
packages/drf_yasg/inspectors/view.py", line 45, in get_operation
responses = self.get_responses()
File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site-
packages/drf_yasg/inspectors/view.py", line 180, in get_responses
response_serializers = self.get_response_serializers()
File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site-
packages/drf_yasg/inspectors/view.py", line 235, in get_response_serializers
responses = self.get_default_responses()
File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site-
packages/drf_yasg/inspectors/view.py", line 211, in get_default_responses
default_schema = self.serializer_to_schema(default_schema) or ''
File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site-
packages/drf_yasg/inspectors/base.py", line 446, in serializer_to_schema
self.field_inspectors, 'get_schema', serializer, {'field_inspectors':
self.field_inspectors}
File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site-
packages/drf_yasg/inspectors/base.py", line 118, in probe_inspectors
result = method(obj, **kwargs)
File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site-
packages/drf_yasg/inspectors/field.py", line 42, in get_schema
return self.probe_field_inspectors(serializer, openapi.Schema, self.use_definitions)
File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site-
packages/drf_yasg/inspectors/base.py", line 238, in probe_field_inspectors
swagger_object_type=swagger_object_type, use_references=use_references, **kwargs
File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site-
packages/drf_yasg/inspectors/base.py", line 118, in probe_inspectors
result = method(obj, **kwargs)
File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site-
packages/drf_yasg/inspectors/field.py", line 83, in field_to_swagger_object
SwaggerType, ChildSwaggerType = self._get_partial_types(field, swagger_object_type,
use_references, **kwargs)
File "/Users/admin/Desktop/food-delivery-app-19083590-python/env/lib/python3.7/site-
packages/drf_yasg/inspectors/base.py", line 273, in _get_partial_types
title = force_real_str(field.label) if field.label else None
AttributeError: 'Response' object has no attribute 'label'
HTTP GET /swagger/?format=openapi 500 [2.48, 127.0.0.1:51305]
setting.py
INSTALLED_APPS=[
...
'drf_yasg',
...
]
SWAGGER_SETTINGS = {
'SECURITY_DEFINITIONS': {
'basic': {
'type': 'basic'
}
},
}
urls.py
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
schema_view = get_schema_view(
openapi.Info(
title="Food Delivery Application",
default_version='0.1',
description="Test description",
),
public=True,
permission_classes=(permissions.AllowAny,),
)
urlpatterns = [
...
url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
...
]
After spending hours on my code, I finally made it working. drf-yasg won't work fine when its comes to overriding functions like get_queryset()and get_serializer() and filtering out the data of authenticated user using self.request.user Use below coding technique to fix the issue:
def get_queryset(self):
if getattr(self, 'swagger_fake_view', False):
return MyModel.objects.none() # return empty queryset
return self.queryset.filter(user=self.request.user)
To know more click here
I'm writing a test for a function that returns a JSONResponse. The function works fine on the website but the test always raises a TypeError. It looks like the program fails to get an entry from the database and returns an error instead.
views.py:
def check_availability(request, id):
if request.method == "GET":
response_data = {}
event_date = request.GET.get('event_date', False)
check = None
try:
try:
speaker = Pembicara.objects.get(id = id)
filtered = Booking.objects.filter(speaker = speaker)
check = filtered.get(event_date = event_date)
except ObjectDoesNotExist as e:
pass
except Exception as e:
raise e
if not check:
response_data['available'] = 'ok'
else:
response_data['available'] = 'no'
except Exception as e:
raise e
return JsonResponse(response_data)
tests.py:
def test_date_availability_is_checked(self):
p = self.createPembicara()
c = Client()
date = datetime.date.today()
# request = c.get('/profile/1/check_availability/', event_date=date)
b = self.createBooking()
request = c.get('/profile/1/check_availability/', event_date='1999-12-20')
self.assertEqual(request.status_code, 200)
self.assertJSONEqual(request.content, {'available': 'ok'})
terminal:
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
./Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/whitenoise/base.py:116: UserWarning: No directory at: /Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/BookaSpeakers/static/
warnings.warn(u"No directory at: {}".format(root))
E.......
======================================================================
ERROR: test_date_availability_is_checked (speaker_profile.tests.ProfileTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/speaker_profile/tests.py", line 69, in test_date_availability_is_checked
request = c.get('/profile/1/check_availability/', event_date='2000-12-20')
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/test/client.py", line 535, in get
response = super().get(path, data=data, secure=secure, **extra)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/test/client.py", line 347, in get
**extra,
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/test/client.py", line 422, in generic
return self.request(**r)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/test/client.py", line 503, in request
raise exc_value
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/speaker_profile/views.py", line 53, in check_availability
raise e
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/speaker_profile/views.py", line 47, in check_availability
raise e
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/speaker_profile/views.py", line 43, in check_availability
check = filtered.get(event_date = event_date)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/query.py", line 399, in get
clone = self.filter(*args, **kwargs)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/query.py", line 892, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/query.py", line 910, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1290, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1318, in _add_q
split_subq=split_subq, simple_col=simple_col,
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1251, in build_filter
condition = self.build_lookup(lookups, col, value)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1116, in build_lookup
lookup = lookup_class(lhs, rhs)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/lookups.py", line 20, in __init__
self.rhs = self.get_prep_lookup()
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/lookups.py", line 70, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 1270, in get_prep_value
return self.to_python(value)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 1232, in to_python
parsed = parse_date(value)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/utils/dateparse.py", line 74, in parse_date
match = date_re.match(value)
TypeError: expected string or bytes-like object
----------------------------------------------------------------------
Ran 9 tests in 0.211s
FAILED (errors=1)
Destroying test database for alias 'default'...
Any help would be appreciated, thank you!
The error likely happens because event_date ends up with the value False, which happens because there was no value for 'event_date' in request.GET.
According to the docs of Client.get(), you have to pass a dict with the GET/POST parameters of the request, not using kwargs.
Try by changing this line (which is using kwargs):
request = c.get('/profile/1/check_availability/', event_date='1999-12-20')
to this (now using a dict as the second parameter)
request = c.get('/profile/1/check_availability/', {'event_date': '1999-12-20'})
I have a big dictionary with more than 50 items. I am trying to return this dictionary in the form of JSON.
The code for that is:-
return HttpResponse(json.dumps(responseData, indent = 0, default=str), content_type="application/json")
There are some date fields in the dictionary and so I mentioned default=str to convert them to string.
When I print the json.dumps, I do see proper values present in the json. But when I put it in HttpResponse, I get the below error:-
too many values to unpack (expected 2)
Could somebody tell me why exactly its happening and what is the workaround?
EDIT:- TRACEBACK
Internal Server Error: /ScApp2/home/App20/Details/
Traceback (most recent call last):
File "\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
response = get_response(request)
File "\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "\PythonWorkspace\ScApp\ScApp2\views.py", line 88, in ModelDetails
cmsPointScore = PspstCmspointscore.objects.filter(model_id)
File "\Python\Python37\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "\Python\Python37\lib\site-packages\django\db\models\query.py", line 836, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "\Python\Python37\lib\site-packages\django\db\models\query.py", line 854, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "\Python\Python37\lib\site-packages\django\db\models\sql\query.py", line 1253, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "\Python\Python37\lib\site-packages\django\db\models\sql\query.py", line 1277, in _add_q
split_subq=split_subq,
File "\Python\Python37\lib\site-packages\django\db\models\sql\query.py", line 1150, in build_filter
arg, value = filter_expr
ValueError: too many values to unpack (expected 2)
The error is in your query (that's why I asked for the traceback):
cmsPointScore = PspstCmspointscore.objects.filter(model_id)
You should add the field name to the filter expression, for example:
cmsPointScore = PspstCmspointscore.objects.filter(model_id=model_id)