I'm having an issue building a list of dictionaries like this
#login_required(login_url="login/")
def home(request):
user = StaticHelpers.user_to_subclass(request.user)[1]
user_type = StaticHelpers.user_to_subclass(request.user)[0]
if user_type == "Patient":
apps = StaticHelpers.find_appointments(user)
events = []
for app in apps:
events.append({
'title': str(app.doctor),
'start': str(app.start_time),
'end': str(app.end_time)
})
return render(request, 'HealthApp/patientIndex.html', events)
elif user_type == "Doctor" or user_type == "Nurse":
return render(request, 'HealthApp/doctorIndex.html')
elif user_type == "Admin":
return render(request, 'HealthApp/doctorIndex.html')
Each dictionary needs to have those 3 values, and I need a list of them. However it just spits out this error at me
Internal Server Error: /
Traceback (most recent call last):
File "/home/devin-matte/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/home/devin-matte/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/devin-matte/.local/lib/python3.5/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/devin-matte/Documents/Healthnet/trunk/HealthApp/views.py", line 23, in home
return render(request, 'HealthApp/patientIndex.html', events)
File "/home/devin-matte/.local/lib/python3.5/site-packages/django/shortcuts.py", line 67, in render
template_name, context, request=request, using=using)
File "/home/devin-matte/.local/lib/python3.5/site-packages/django/template/loader.py", line 97, in render_to_string
return template.render(context, request)
File "/home/devin-matte/.local/lib/python3.5/site-packages/django/template/backends/django.py", line 92, in render
context = make_context(context, request)
File "/home/devin-matte/.local/lib/python3.5/site-packages/django/template/context.py", line 291, in make_context
context.push(original_context)
File "/home/devin-matte/.local/lib/python3.5/site-packages/django/template/context.py", line 61, in push
return ContextDict(self, *dicts, **kwargs)
File "/home/devin-matte/.local/lib/python3.5/site-packages/django/template/context.py", line 20, in __init__
super(ContextDict, self).__init__(*args, **kwargs)
ValueError: dictionary update sequence element #0 has length 3; 2 is required
[05/Mar/2017 19:56:17] "GET / HTTP/1.1" 500 99419
The traceback shows that the problem is nothing to do with creating the dictionaries, but in how you send them to the template. The third argument to render must be a dict, where the keys are the name you want to use to refer to that value in the template. So:
return render(request, 'HealthApp/patientIndex.html', {"events": events})
Now you can iterate through events in the template.
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',
})
I have a created a simple Python program, which will retrieve and add data to database based on the user input. I used POST method for this. The program is successfully working in Postman, but when I call the program from an iOS app using API call, the program is showing 500 error. The errors are in exception.py and base.py. My program is given below
#api_view(["POST"])
def mg_grt(request):
if request.method == 'POST':
name = request.POST['name']
word = name.lower()
greet = Greet.objects.filter(grett=word)
if greet != 0:
d = Resp(rsp=word)
d.save()
r_val = Resp.objects.all()
rt = random.choice(r_val)
return HttpResponse(rt)
else:
return HttpResponse("Sorry...I didn't understand")
else:
return HttpResponse("Bad Request")
The errors are:
File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 483, in dispatch
response = self.handle_exception(exc)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 443, in handle_exception
self.raise_uncaught_exception(exc)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 480, in dispatch
response = handler(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/rest_framework/decorators.py", line 53, in handler
return func(*args, **kwargs)
File "/Users/abijith/Test5/tgpi/views.py", line 21, in mg_grt
name = request.POST['name']
File "/Library/Python/2.7/site-packages/django/utils/datastructures.py", line 85, in __getitem__
raise MultiValueDictKeyError(repr(key))
MultiValueDictKeyError: "u'name'"
[31/Aug/2018 10:20:45] "POST /grt/ HTTP/1.1" 500 14099
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.
I am attempting to update an extended user model profile in admin.py actions. I have been researching this for a couple hours now and have come up short. I am receiving a pc_add_1() missing 1 required positional argument: 'queryset' error, please help.
class ProfileAdminInLine(admin.StackedInline):
model = Profile
class ProfileAdmin(UserAdmin):
list_display = ['username', 'email', 'first_name', 'last_name', 'is_staff',
'rewards_punch_card', 'rewards_tier', 'credits']
list_select_related = True
inlines = [ProfileAdminInLine]
actions = ['pc_add_1', 'pc_add_2', 'pc_add_3', 'pc_add_4', 'pc_add_5',
'pc_add_6', 'pc_add_7', 'pc_add_8', 'pc_add_9']
def rewards_tier(self, user):
return user.profile.rewards_tier
def rewards_punch_card(self, user):
return user.profile.rewards_current
def pc_add_1(self, request, user, queryset):
punch_card = user.profile.rewards_current
tier = user.profile.rewards_tier
credits = user.profile.rewards_credits
punch_cards_updated = queryset.update(punch_card + 1)
if punch_cards_updated == 10:
queryset.update(punch_card == 0)
if tier == 1:
queryset.update(tier + 1)
queryset.update(credits + 25)
elif tier == 2:
queryset.update(tier + 1)
queryset.update(credits + 35)
elif tier == 3:
queryset.update(tier + 1)
queryset.update(credits + 45)
elif tier == 4:
queryset.update(tier + 1)
queryset.update(credits + 55)
elif tier == 5:
queryset.update(credits + 65)
elif tier == 6:
queryset.update(credits + 65)
else:
pass
traceback
Internal Server Error: /admin/auth/user/
Traceback (most recent call last):
File "/usr/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
response = get_response(request)
File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.5/site-packages/django/contrib/admin/options.py", line 544, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/local/lib/python3.5/site-packages/django/utils/decorators.py", line 149, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.5/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.5/site-packages/django/contrib/admin/sites.py", line 211, in inner
return view(request, *args, **kwargs)
File "/usr/local/lib/python3.5/site-packages/django/utils/decorators.py", line 67, in _wrapper
return bound_func(*args, **kwargs)
File "/usr/local/lib/python3.5/site-packages/django/utils/decorators.py", line 149, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.5/site-packages/django/utils/decorators.py", line 63, in bound_func
return func.__get__(self, type(self))(*args2, **kwargs2)
File "/usr/local/lib/python3.5/site-packages/django/contrib/admin/options.py", line 1569, in changelist_view
response = self.response_action(request, queryset=cl.get_queryset(request))
File "/usr/local/lib/python3.5/site-packages/django/contrib/admin/options.py", line 1305, in response_action
response = func(self, request, queryset)
TypeError: pc_add_1() missing 1 required positional argument: 'queryset'
[13/Nov/2016 15:16:52] "POST /admin/auth/user/ HTTP/1.1" 500 106710
You have the method signature wrong:
def pc_add_1(self, request, user, queryset):
For admin actions it should be
def pc_add_1(self, request, queryset):
now if you want to know which admin user is making the change you can find that out from request.user
You have to remove the argument user from the line
def pc_add_1(self, request, user, queryset):
Django will call that method with request and queryset only. You will be able to get the user with request.user.