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
Related
I have problem with google auth. Steps to reproduce problem:
Register password account
Try to log in with google auth
Get 500 answer
Traceback:
Internal Server Error: /api/v1/auth/google/
Traceback (most recent call last):
File "/home/andrew/.local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/andrew/.local/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/andrew/.local/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/andrew/.local/lib/python3.10/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/home/andrew/.local/lib/python3.10/site-packages/django/utils/decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "/home/andrew/.local/lib/python3.10/site-packages/django/views/decorators/debug.py", line 89, in sensitive_post_parameters_wrapper
return view(request, *args, **kwargs)
File "/home/andrew/.local/lib/python3.10/site-packages/dj_rest_auth/views.py", line 54, in dispatch
return super().dispatch(*args, **kwargs)
File "/home/andrew/.local/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/home/andrew/.local/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/andrew/.local/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/home/andrew/.local/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/home/andrew/Documents/pets_backend/project/api_v1/views/social.py", line 77, in post
response = super().post(request, *args, **kwargs)
File "/home/andrew/.local/lib/python3.10/site-packages/dj_rest_auth/views.py", line 125, in post
self.serializer.is_valid(raise_exception=True)
File "/home/andrew/.local/lib/python3.10/site-packages/rest_framework/serializers.py", line 220, in is_valid
self._validated_data = self.run_validation(self.initial_data)
File "/home/andrew/.local/lib/python3.10/site-packages/rest_framework/serializers.py", line 422, in run_validation
value = self.validate(value)
File "/home/andrew/.local/lib/python3.10/site-packages/dj_rest_auth/registration/serializers.py", line 151, in validate
complete_social_login(request, login)
File "/home/andrew/.local/lib/python3.10/site-packages/allauth/socialaccount/helpers.py", line 151, in complete_social_login
return _complete_social_login(request, sociallogin)
File "/home/andrew/.local/lib/python3.10/site-packages/allauth/socialaccount/helpers.py", line 172, in _complete_social_login
ret = _process_signup(request, sociallogin)
File "/home/andrew/.local/lib/python3.10/site-packages/allauth/socialaccount/helpers.py", line 22, in _process_signup
url = reverse("socialaccount_signup")
File "/home/andrew/.local/lib/python3.10/site-packages/django/urls/base.py", line 86, in reverse
return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
File "/home/andrew/.local/lib/python3.10/site-packages/django/urls/resolvers.py", line 694, in _reverse_with_prefix
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'socialaccount_signup' not found. 'socialaccount_signup' is not a valid view function or pa
ttern name.
"POST /api/v1/auth/google/ HTTP/1.1" 500 184486
I added to configs
SOCIALACCOUNT_EMAIL_VERIFICATION = "none"
SOCIALACCOUNT_EMAIL_REQUIRED = False
SOCIALACCOUNT_QUERY_EMAIL = False
but not worked.
The field is simple:
timestamp=DateTimeField(primary_key=True)
The timestamps are displayed in this format: "June 12, 2021, 2:40 a.m.".
When I try to delete an entry, it gives me this exception:
Traceback (most recent call last):
File "/home/pooh/venv39/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/pooh/venv39/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/pooh/venv39/lib/python3.9/site-packages/django/contrib/admin/options.py", line 616, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/pooh/venv39/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/home/pooh/venv39/lib/python3.9/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/home/pooh/venv39/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 232, in inner
return view(request, *args, **kwargs)
File "/home/pooh/venv39/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "/home/pooh/venv39/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/home/pooh/venv39/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1739, in changelist_view
response = self.response_action(request, queryset=cl.get_queryset(request))
File "/home/pooh/venv39/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1406, in response_action
queryset = queryset.filter(pk__in=selected)
File "/home/pooh/venv39/lib/python3.9/site-packages/django/db/models/query.py", line 941, in filter
return self._filter_or_exclude(False, args, kwargs)
File "/home/pooh/venv39/lib/python3.9/site-packages/django/db/models/query.py", line 961, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, args, kwargs)
File "/home/pooh/venv39/lib/python3.9/site-packages/django/db/models/query.py", line 968, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "/home/pooh/venv39/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1393, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/home/pooh/venv39/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1412, in _add_q
child_clause, needed_inner = self.build_filter(
File "/home/pooh/venv39/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1347, in build_filter
condition = self.build_lookup(lookups, col, value)
File "/home/pooh/venv39/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1193, in build_lookup
lookup = lookup_class(lhs, rhs)
File "/home/pooh/venv39/lib/python3.9/site-packages/django/db/models/lookups.py", line 25, in __init__
self.rhs = self.get_prep_lookup()
File "/home/pooh/venv39/lib/python3.9/site-packages/django/db/models/lookups.py", line 240, in get_prep_lookup
rhs_value = self.lhs.output_field.get_prep_value(rhs_value)
File "/home/pooh/venv39/lib/python3.9/site-packages/django/db/models/fields/__init__.py", line 1406, in get_prep_value
value = super().get_prep_value(value)
File "/home/pooh/venv39/lib/python3.9/site-packages/django/db/models/fields/__init__.py", line 1266, in get_prep_value
return self.to_python(value)
File "/home/pooh/venv39/lib/python3.9/site-packages/django/db/models/fields/__init__.py", line 1388, in to_python
raise exceptions.ValidationError(
django.core.exceptions.ValidationError: ['“June 12, 2021, 2:40 a.m.” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']
[17/Nov/2021 20:04:01] "POST /admin/micogui/transaction/ HTTP/1.1" 500 162676
I've investigated, it's because of the intermediate delete confirmation dialog. When invoking the "delete selected items" action it sends the request with all the entries in correct format (YYYY-MM-DD...), but then after confirmation dialog I see this in the delete_selected_confirmation.html:
<input type="hidden" name="{{ action_checkbox_name }}" value="{{ obj.pk|unlocalize }}">
After this timestamp is being sent in the format I see on page (June 12, ...) and the code hiccups.
It will require someone from django developers to understand how to fix it best, I'm afraid.
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 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