When I try to add an url attribute to my model I get this error:
AttributeError: 'collections.OrderedDict' object has no attribute 'pk'
These are the codes I use. I tried a lot of things but just get an error with everything I try..
Serializer:
class GroupPatchSerializer(serializers.ModelSerializer):
linked_sites = serializers.ListField()
name = serializers.CharField(required=False)
url = serializers.HyperlinkedIdentityField(
view_name="group-detail", lookup_url_kwarg="group_pk"
)
class Meta:
model = Group
fields = ("id", "url", "name", "linked_sites")
def validate_linked_sites(self, sites):
** code **
return sites
# noinspection PyMethodMayBeStatic
def validate_name(self, name):
** code **
return name
view:
def patch(self, request, group_pk):
"""
Add site to group, change an existing group's name.
-id: The group's id
"""
user = request.user
group_id = int(group_pk)
group = Group.objects.filter(pk=group_id).first()
# Update the group
serializer_class = self.get_serializer_class()
serializer = serializer_class(
data=self.request.data,
context={"request": request, "user_pk": user.id, "group_id": group_id},
)
test-class:
def test_ok_authorized_access(self):
# Login the user
self.client.force_login(self.user_1)
UserSiteFactory(user=self.user_1, site=self.test_site_3)
# Get the url
url = reverse("group-detail", kwargs={"group_pk": self.test_group_1.pk})
# New group name
new_name = "New group name"
sites = [self.test_site_3.pk]
# Execute the patch operation
response = self.client.patch(
url, data={"name": new_name, "linked_sites": sites}
)
# Test if there was no error
self.assertEqual(response.status_code, status.HTTP_200_OK)
# Test if the group was renamed
group = Group.objects.all().filter(pk=self.test_group_1.pk).first()
self.assertEqual(group.name, new_name)
stacktrace
Traceback (most recent call last):
File "/opt/project/backend/groups/tests/test_group_patch.py", line 45, in test_ok_authorized_access
url, data={"name": new_name, "linked_sites": sites}
File "/usr/local/lib/python3.6/site-packages/rest_framework/test.py", line 310, in patch
path, data=data, format=format, content_type=content_type, **extra)
File "/usr/local/lib/python3.6/site-packages/rest_framework/test.py", line 215, in patch
return self.generic('PATCH', path, data, content_type, **extra)
File "/usr/local/lib/python3.6/site-packages/rest_framework/test.py", line 232, in generic
method, path, data, content_type, secure, **extra)
File "/usr/local/lib/python3.6/site-packages/django/test/client.py", line 422, in generic
return self.request(**r)
File "/usr/local/lib/python3.6/site-packages/rest_framework/test.py", line 283, in request
return super().request(**kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/test.py", line 235, in request
request = super().request(**kwargs)
File "/usr/local/lib/python3.6/site-packages/django/test/client.py", line 503, in request
raise exc_value
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/usr/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 "/usr/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 "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/viewsets.py", line 114, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
raise exc
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "/opt/project/backend/groups/views/group_detail_view.py", line 108, in patch
return Response(serializer.data, status=status.HTTP_200_OK)
File "/usr/local/lib/python3.6/site-packages/rest_framework/serializers.py", line 559, in data
ret = super().data
File "/usr/local/lib/python3.6/site-packages/rest_framework/serializers.py", line 263, in data
self._data = self.to_representation(self.validated_data)
File "/usr/local/lib/python3.6/site-packages/rest_framework/serializers.py", line 526, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "/usr/local/lib/python3.6/site-packages/rest_framework/relations.py", line 393, in to_representation
url = self.get_url(value, self.view_name, request, format)
File "/usr/local/lib/python3.6/site-packages/rest_framework/relations.py", line 329, in get_url
lookup_value = getattr(obj, self.lookup_field)
AttributeError: 'collections.OrderedDict' object has no attribute 'pk'
From the DRF docs on HyperlinkedIdentityField:
lookup_field - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is 'pk'.
lookup_url_kwarg - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as lookup_field.
So you're setting lookup_url_kwarg directly, but you're not changing lookup_field, which is where your error is coming from. Because lookup_url_kwarg defaults to the same value as lookup_field, we can just use that:
class GroupPatchSerializer(serializers.ModelSerializer):
# code...
url = serializers.HyperlinkedIdentityField(
view_name="group-detail", lookup_field="group_pk"
)
# code...
Related
Here I am using an api of notifications. here is the reference of that api link. I have follow the instructions given on the github read me file. But when i try to send an email by actor to recipient .it shows me the error 'int' object has no attribute '_meta'. The actor field and recipient both accept user_ids and I have put them manually. But still didn't work.
profiles/Views.py
class UserProfileFollowToggle(LoginRequiredMixin,View):
login_url = '/accounts/login/'
def post(self, request, *args, **kwargs):
user_to_toggle_pk=kwargs.get('pk')
username_to_toggle = request.POST.get("username")
profile_, is_following = UserProfile.objects.toggle_follow(request.user, request.user.id, user_to_toggle_pk ,username_to_toggle)
return redirect(f'/profiles/{username_to_toggle}')
profiles/models.py
class ProfileManager(models.Manager):
def toggle_follow(self, request_user,user_id,user_to_toggle_pk, username_to_toggle):
profile_ = UserProfile.objects.get(user__username__iexact=request_user.username)
is_following = False
follower = profile_.follower.filter(username__iexact=username_to_toggle).first()
if follower:
profile_.follower.remove(follower.id)
notify.send(user_id, recipient=user_to_toggle_pk, verb='unfollow you')
else:
new_follower = User.objects.get(username__iexact=username_to_toggle)
profile_.follower.add(new_follower.id)
notify.send(user_id, recipient=user_to_toggle_pk, verb='follow you')
is_following = True
return profile_, is_following
traceback:
Traceback (most recent call last):
File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\AHMED\anaconda3\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\AHMED\anaconda3\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch
return super().dispatch(request, *args, **kwargs)
File "C:\Users\AHMED\anaconda3\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\AHMED\grapPub\grabpublic\profiles\views.py", line 30, in post
profile_, is_following = UserProfile.objects.toggle_follow(request.user, request.user.id, user_to_toggle_pk ,username_to_toggle)
File "C:\Users\AHMED\grapPub\grabpublic\profiles\models.py", line 22, in toggle_follow
notify.send(user_id, recipient=user_to_toggle_pk, verb='unfollow you')
File "C:\Users\AHMED\anaconda3\lib\site-packages\django\dispatch\dispatcher.py", line 173, in send
return [
File "C:\Users\AHMED\anaconda3\lib\site-packages\django\dispatch\dispatcher.py", line 174, in <listcomp>
(receiver, receiver(signal=self, sender=sender, **named))
File "C:\Users\AHMED\grapPub\grabpublic\notifications\base\models.py", line 288, in notify_handler
actor_content_type=ContentType.objects.get_for_model(actor),
File "C:\Users\AHMED\anaconda3\lib\site-packages\django\contrib\contenttypes\models.py", line 40, in get_for_model
opts = self._get_opts(model, for_concrete_model)
File "C:\Users\AHMED\anaconda3\lib\site-packages\django\contrib\contenttypes\models.py", line 27, in _get_opts
model = model._meta.concrete_model
Exception Type: AttributeError at /profiles/user-profile/2/
Exception Value: 'int' object has no attribute '_meta'
If more information is required than tell me in a comment section. I will update my question with that information.
I think the AttributeError is caused, because you are trying to pass a user pk to the send function
notify.send(user_id, recipient=user_to_toggle_pk, verb='unfollow you')
^^^^^^^^^^^^^^^^
but the send function expect an User object.
So try something like this..
user = User.objects.get(pk=user_to_toggle_pk)
notify.send(user_id, recipient=user, verb='unfollow you')
Is it a correct way to apply celery to class based views?
And, if it is, how can I apply celery to class based Views?
I can’t apply just tagging #app.task above functions inside class.
class ScheduleByFranchiseIdView(generics.RetrieveAPIView):
permission_classes = (IsAdmin,)
serializer_class = ScheduleSerializer
#app2.task
def get(self, request, franchise_id, start = None, end = None):
if start != None and end != None:
query1 = Q(student__profile__franchise__exact=franchise_id)
query2 = Q(start_time__gte=start)
query3 = Q(end_time__lt=end)
queryset = Schedule.objects.filter(query1 & query2 & query3).exclude(status=ScheduleStatus.DELETED).order_by('-id')
serializer = ScheduleSerializer(queryset, many=True)
else:
query1 = Q(student__profile__franchise__exact=franchise_id)
queryset = Schedule.objects.filter(query1).exclude(status=ScheduleStatus.DELETED).order_by('-id')
serializer = ScheduleSerializer(queryset, many=True)
return Response(serializer.data)
I'm trying to test this api and when I call HTTP GET Method to call this api,
i get the error below:
Traceback (most recent call last):
File "C:\Users\Tonyscoding\Desktop\TOCOL\TOCOL_backend\api\testing\test_pagination.py", line 154, in test_admin_schedule_pagination
response = self.client.get('/api/schedule/by/franchise/simple/1/')
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\rest_framework\test.py", line 286, in get
response = super().get(path, data=data, **extra)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\rest_framework\test.py", line 203, in get
return self.generic('GET', path, **r)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\rest_framework\test.py", line 232, in generic
method, path, data, content_type, secure, **extra)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\django\test\client.py", line 422, in generic
return self.request(**r)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\rest_framework\test.py", line 283, in request
return super().request(**kwargs)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\rest_framework\test.py", line 235, in request
request = super().request(**kwargs)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\django\test\client.py", line 503, in request
raise exc_value
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\rest_framework\views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
raise exc
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\rest_framework\views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\celery\local.py", line 191, in __call__
return self._get_current_object()(*a, **kw)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\celery\app\task.py", line 392, in __call__
return self.run(*args, **kwargs)
TypeError: get() missing 1 required positional argument: 'request'
my celery worker get the task. I think it's not a worker problem..
In your case might work next scenario. Create a task for hard workload:
#app.task
def schedule_by_franchise(franchise_id, start=None, end=None):
# Do some slow workload, filtering by non-indexed fields or something.
if start is not None and end is not None: # is not None ~20% faster than != None
query1 = Q(student__profile__franchise__exact=franchise_id)
query2 = Q(start_time__gte=start)
query3 = Q(end_time__lt=end)
queryset = Schedule.objects.filter(query1 & query2 & query3).exclude(status=ScheduleStatus.DELETED).order_by('-id')
else:
query1 = Q(student__profile__franchise__exact=franchise_id)
queryset = Schedule.objects.filter(query1).exclude(status=ScheduleStatus.DELETED).order_by('-id')
# Returns something serializable and what could be used for more faster DB search (founded object primary keys might fits)
return tuple(queryset.values_list('id', flat=True))
When executed first GET you should create Celery task and then save it TASK_ID somewhere to later get result:
from celery.result import AsyncResult
class ScheduleByFranchiseIdView(generics.RetrieveAPIView):
permission_classes = (IsAdmin,)
serializer_class = ScheduleSerializer
def get(self, request, franchise_id, start=None, end=None, task_id=None):
if not task_id:
task = schedule_by_franchise.delay(franchise_id, start, end)
return Response({
'task': task.task_id,
'status': 'processing',
'message': f'Please, try again in 10 seconds with following task_id={task.task_id}',
})
else:
result = AsyncResult(task_id)
if result.ready():
ids = result.result
queryset = Schedule.objects.filter(id__in=ids)
serializer = ScheduleSerializer(queryset, many=True)
return Response(serializer.data)
else:
return Response({
'status': 'not_ready_yet',
'message': 'Please, try again in 5 seconds',
})
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 have a file that sends a request to an API and retrieves information. Let's call this file get_info.py. I am now building a GUI that uses Django and the views.py file, with methods 'GET' and 'POST'.
I am now importing the function from get_info.py into views.py and using it as follows
from get_info import get_info
#api_view(['GET'])
def generate_route(request):
"""
:param request:
1. lat: posx
2. lng: pos,
3. r: radius in km
4. strategy,
5. edge_num,
6. deep,
:return:
"""
posx = request.query_params.get('lat', None)
posy= request.query_params.get('lng', None)
r= request.query_params.get('r', None)
strategy = request.query_params.get('strategy', None)
strategy = strategy if strategy else 3
edge_num = request.query_params.get('edge_num', None)
edge_num = edge_num if edge_num else 3
deep = request.query_params.get('deep', None)
deep = deep if deep else 3
print("BEFORE", posx, posy, r, strategy, edge_num, deep)
route = get_info(posx, posy, r)
print("AFTER", route)
if request.query_params.get('lat', None) is not None \
and request.query_params.get('lng', None) is not None \
and request.query_params.get('r', None) is not None:
return Response({}, status=status.HTTP_200_OK)
else:
return Response({
"Error": 'Need lat, lng, and r {}'.format(request.query_params.get('lat', None))
}, status=status.HTTP_400_BAD_REQUEST)
```
However, I get the response
> (u'BEFORE', u'112.34', u'14.55', u'300.3', 3, 3, 3)
Internal Server Error: /app/api/v1/get_info/
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 249, in _legacy_get_response
response = self._get_response(request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 483, in dispatch
response = self.handle_exception(exc)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 443, in handle_exception
self.raise_uncaught_exception(exc)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 480, in dispatch
response = handler(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/decorators.py", line 53, in handler
return func(*args, **kwargs)
File "/home/user/Projects/app/views.py", line 750, in generate_route
route = get_info(posx, posy, r)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 466, in dispatch
request = self.initialize_request(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 370, in initialize_request
parser_context=parser_context
File "/usr/local/lib/python2.7/dist-packages/rest_framework/request.py", line 159, in __init__
.format(request.__class__.__module__, request.__class__.__name__)
AssertionError: The `request` argument must be an instance of `django.http.HttpRequest`, not `__builtin__.unicode`.
But when I use from django.http import HttpRequest to build my request, it tells me 'maximum depth exceeded'.
The get_info method is quite long, but in a nutshell it looks like this:
def get_info(posx, posy, r, strategy=3, edge_num=0.8, deep=0):
req_url = "http://api.map.baidu.com/direction/v2/driving?origin=posx..."
trip = requests.get(req_url).json()
return trip
When I run this get_info method in my python shell, it returns the desired trip.
If you look closely rest framework is the one which is causing the problem, If the getinfo is an APIView then it might need request as its first argument not posx which is a string.
While uploading an ImageFile to a Django REST backend I am encountering the following error:
Internal Server Error: /user/addimage/
Traceback (most recent call last):
File "/home/neuron/genie2_env/lib/python3.4/site-packages/django/core/handlers/exception.py", liner
response = get_response(request)
File "/home/neuron/genie2_env/lib/python3.4/site-packages/django/core/handlers/base.py", line 187,e
response = self.process_exception_by_middleware(e, request)
File "/home/neuron/genie2_env/lib/python3.4/site-packages/django/core/handlers/base.py", line 185,e
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/neuron/genie2_env/lib/python3.4/site-packages/django/views/decorators/csrf.py", line 5w
return view_func(*args, **kwargs)
File "/home/neuron/genie2_env/lib/python3.4/site-packages/django/views/generic/base.py", line 68, w
return self.dispatch(request, *args, **kwargs)
File "/home/neuron/genie2_env/lib/python3.4/site-packages/rest_framework/views.py", line 489, in dh
response = self.handle_exception(exc)
File "/home/neuron/genie2_env/lib/python3.4/site-packages/rest_framework/views.py", line 449, in hn
self.raise_uncaught_exception(exc)
File "/home/neuron/genie2_env/lib/python3.4/site-packages/rest_framework/views.py", line 486, in dh
response = handler(request, *args, **kwargs)
File "/home/neuron/genie2/user_profiles/views.py", line 92, in post
profile_stored = file_system_instance.save('profile_' + data['first_name'] + ".jpg", request.FIL)
File "/home/neuron/genie2_env/lib/python3.4/site-packages/django/core/files/storage.py", line 54, e
return self._save(name, content)
File "/home/neuron/genie2_env/lib/python3.4/site-packages/django/core/files/storage.py", line 351,e
for chunk in content.chunks():
File "/home/neuron/genie2_env/lib/python3.4/site-packages/django/core/files/base.py", line 81, in s
data = self.read(chunk_size)
File "/home/neuron/genie2_env/lib/python3.4/site-packages/django/core/files/utils.py", line 16, in>
read = property(lambda self: self.file.read)
AttributeError: 'NoneType' object has no attribute 'read'
[01/Aug/2017 14:14:22] "POST /user/addimage/ HTTP/1.1" 500 18686
My View:
class AddImage(APIView):
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
def post(self, request):
user_serialized = ContactNumberUserSerializer(instance=self.request.user)
data = user_serialized.data
instance = ContactNumberUser.objects.get(contact=data['contact'])
profile_img_instance = ImageFile(request.FILES.get('profile_pic'))
file_system_instance = FileSystemStorage(location=settings.MEDIA_ROOT)
instance.profile_pic = file_system_instance.save('profile_' + data['first_name'] + ".jpg", profile_img_instance)
instance.save()
return Response(status=status.HTTP_200_OK)
Am I doing it completely wrong somehow? If yes, please suggest a better solution.
Django REST Framework 3 deprecated the request.FILES option.You can use request.data for the imagefield.
Change
request.FILES.get('profile_pic')
to
request.data.get('profile_pic')
If you defined ImageField or FileField , you do not need to upload file manually. Django will do it for you
Instead of this code,
profile_img_instance = ImageFile(request.FILES.get('profile_pic'))
file_system_instance = FileSystemStorage(location=settings.MEDIA_ROOT)
instance.profile_pic = file_system_instance.save('profile_' + data['first_name'] + ".jpg", profile_img_instance)
Directly assign image to field,
instance.profile_pic = request.data.get('profile_pic')
Also make sure your model field look like this,
class Model(models.Model):
profile_pic = models.ImageField(upload_to='profile')