AttributeError: 'bytes' object has no attribute - django

I have a class in which I am checking user permissions, and depending on them, I return a list of results from models. Here is what I have:
from AnnualLeave.models import Leaves, RejectedLeaves, Employee
class GetLeaves:
def get_results(request):
try:
if request.user.groups.filter(name__in=['SuperAdmin']).exists():
return Leaves.objects.all()
elif request.user.groups.filter(name__in=['Admin']).exists():
return Leaves.objects.filter(employee_id=Employee.objects.get(manager_id=request.user.pk))
else:
messages.error(request, "You are not allowed on this page")
return render(request, 'users/home.html')
except (Leaves.DoesNotExist, Employee.DoesNotExist):
return []
def process_results(request):
leave_request = []
for leave in GetLeaves.get_results(request):
content = {'emp_id': leave.employee_id,
'emp_name': Employee.objects.get(user_id=leave.employee_id).user.get_full_name(),
'start_date': leave.start_date,
'end_date': leave.end_date,
'reason': leave.get_reason_display(),
'description': leave.description,
}
....
leave_request.append(content)
return leave_request
And then I'm calling process_results function in TemplateView like this:
class ProcessLeaveRequest(TemplateView):
template_name = 'LMSAdmin/process_leave_request.html'
def get(self, request, *args, **kwargs):
return render(request, self.template_name, {'leave_requests': GetLeaves.process_results(request)})
Here is a traceback of error:
Internal Server Error: /lms_admin/upcomingleaves/
Traceback (most recent call last):
File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "D:\Projects\LMS\LMSAdmin\views.py", line 77, in get
for leave in GetLeaves.process_results(request):
File "D:\Projects\LMS\LMSAdmin\views.py", line 39, in process_results
content = {'emp_id': leave.employee_id,
AttributeError: 'bytes' object has no attribute 'employee_id'
From what I can see, it is reading the entire webpage with the request parameter in functions. Like the get_results function is not returning a list, but the entire webpage. I do not understand why this is happening because it was working fine before without any changes.

You should not return a HttpRequest from get_results. Instead raise a PermissionDenied error.
else:
from django.core.exceptions import PermissionDenied
messages.error(request, "You are not allowed on this page")
raise PermissionDenied
If you want to redirect to a different page, handle that in the view. You can capture the PermissionDenied and return the redirect.

Related

Attribute error 'QueryDict' object has no attribute '_meta'

I'm trying to send a post request from PostMan into my Django view and I'm getting this error. "AttributeError: 'QueryDict' object has no attribute '_meta'"
From what I've gathered it has something to do with the form.save() as seen in traceba
I've searched all over to find a solution or even a better way to achieve an image post from a external web client to a Django server.
All help is very much appreciated.
Traceback
Capture.PNG
form is valid
Internal Server Error: /getimg/
Traceback (most recent call last):
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
raise exc
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\decorators.py", line 50, in handler
return func(*args, **kwargs)
File "C:\Users\Gedit\Desktop\django\indivproj\getimg\api\views.py", line 21, in getimg
form.save()
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\serializers.py", line 207, in save
self.instance = self.update(self.instance, validated_data)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\serializers.py", line 979, in update
info = model_meta.get_field_info(instance)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\utils\model_meta.py", line 35, in get_field_info
opts = model._meta.concrete_model._meta
AttributeError: 'QueryDict' object has no attribute '_meta'
[24/Mar/2020 13:39:25] "POST /getimg/ HTTP/1.1" 500 20251
Views.py
#api_view(['POST',])
def getimg(request):
if request.method == 'POST':
form = ImageSerializer(request.POST, request.FILES)
logger.warning(request.FILES['img'])
if form.is_valid():
#raise_exception=True
logger.warning('form is valid')
form.save()
logger.warning()
response_dict = {'post': 'success'}
return HttpResponse(simplejson.dumps(response_dict), content_type='application/javascript')
else:
logger.warning(form.errors)
else:
form = ImageSerializer()
return render(request, 'getimg.html', {'form': form})
Serializers.py
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
fields = '__all__'
Models.py
class Image(models.Model):
# name = models.CharField(default='name', max_length=30)
img = models.ImageField(upload_to='images/', max_length=1000)
Urls.py
app_name = 'getimg'
urlpatterns = [
# ex: /polls/
path('', views.getimg, name='getimg'),
path('gettext/', views.gettext, name='gettext'),
path('success', views.success, name = 'success'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Postman
so after looking around as a smart individual I realized i have not defined what save() function is... so now i do
The code that fixed the error but still not working
def save(self):
img = Image(
img =self.validated_data['img'],
)

Model turns into tuple in django's view. Whata hell?

I am trying to save a string (session hash) into django's model, but something is going wrong..
When I try to update the string, the model turns into a tuple causing AttributeError.
At the beginning everything was in a one 'post' function in view and yet not working. I tried to devide that stuff into functions, but it still does not help. Before the assignment type(session) says that 'session' is a model, not tuple.
View function code:
def post(self, request, *args, **kwargs):
data = json.loads(request.body.decode('utf-8'))
form = self.form_class(data)
if form.is_valid():
phone = form.cleaned_data.get('phone')
code = form.cleaned_data.get('code')
password = form.cleaned_data.get('password')
session = Session.objects.get_or_create(phone=phone, user=request.user.telegramuser)
if code and password:
return utils.sign_in(session, phone, code, password)
elif code:
return utils.sign_in(session, phone, code)
elif phone:
return utils.send_code_request(session, phone)
return JsonResponse({'state': 'none'})
utils.send_code_request and sign_in have the same structure
def send_code_request(session, phone):
result = asyncio.run(_send_code_request(phone))
# result - {
# 'state': 'ok',
# 'session': 'Hfkdi...AaF24s'
# }
if result['state'] == 'ok':
session.update_session(result.pop('session'))
return JsonResponse(result)
Manager
class DefaultManager(models.Manager):
def get_or_create(self, *args, **kwargs):
try:
return self.get(*args, **kwargs)
except ObjectDoesNotExist:
return self.create(*args, **kwargs)
Error:
Internal Server Error: /sessions/add/
Traceback (most recent call last):
File "C:\Users\ipyth\Documents\projects\telegram-sendall\.env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\ipyth\Documents\projects\telegram-sendall\.env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\ipyth\Documents\projects\telegram-sendall\.env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\ipyth\Documents\projects\telegram-sendall\.env\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\ipyth\Documents\projects\telegram-sendall\.env\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch
return super().dispatch(request, *args, **kwargs)
File "C:\Users\ipyth\Documents\projects\telegram-sendall\.env\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\ipyth\Documents\projects\telegram-sendall\sendall\views.py", line 78, in post
return utils.send_code_request(session, phone)
File "C:\Users\ipyth\Documents\projects\telegram-sendall\sendall\utils.py", line 46, in send_code_request
session.update_session(result.pop('session'))
AttributeError: 'tuple' object has no attribute 'update_session'
[23/Jul/2019 23:51:35] "POST /sessions/add/ HTTP/1.1" 500 86600
get_or_create does indeed return a tuple, of the object and a created flag. Either capture both:
session, created = Session.objects.get_or_create(phone=phone...)
Or, use create instead.
Or even better, use the form save method:
session = form.save()

Trouble calling the form constructor from django createview

I tried to pass the user( i.e, request.user) to my modelform constructor as given in this link.But i am getting
TypeError: __init__() got an unexpected keyword argument 'us'
error. Here's my view
class dealAdd(generic.CreateView):
form_class = dealForm
template_name='deals/deal_Add.html'
def get_context_data(self,**kwargs):
context=super(dealAdd,self).get_context_data(**kwargs)
llist=lead.objects.all()
clist=contacts.objects.all()
context.update({'leadob':llist,'contob':clist})
return context
def get_form_kwargs(self, *args, **kwargs):
kwargs = super(dealAdd, self).get_form_kwargs()
kwargs.update({'us': self.request.user})
return kwargs
and my form constructor
def __init__(self,*args,**kwargs):
usr=kwargs.pop('us')
super(dealForm,self).__init__(*args, **kwargs)
print(usr)
# print(self)
the traceback says that i have error at
context=super(dealAdd,self).get_context_data(**kwargs)
So is there a problem in my view?
Traceback:
Internal Server Error: /deals/dealAdd
Traceback (most recent call last):
File "C:\Users\CapC\Desktop\Django\env\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
response = get_response(request)
File "C:\Users\CapC\Desktop\Django\env\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\CapC\Desktop\Django\env\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\CapC\Desktop\Django\env\lib\site-packages\django\views\generic\base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\CapC\Desktop\Django\env\lib\site-packages\django\views\generic\base.py", line 89, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\CapC\Desktop\Django\env\lib\site-packages\django\views\generic\edit.py", line 168, in get
return super().get(request, *args, **kwargs)
File "C:\Users\CapC\Desktop\Django\env\lib\site-packages\django\views\generic\edit.py", line 133, in get
return self.render_to_response(self.get_context_data())
File "C:\Users\CapC\Desktop\Sabith\crm1\deals\views.py", line 21, in get_context_data
context=super(dealAdd,self).get_context_data(**kwargs)
File "C:\Users\CapC\Desktop\Django\env\lib\site-packages\django\views\generic\edit.py", line 66, in get_context_data
kwargs['form'] = self.get_form()
File "C:\Users\CapC\Desktop\Django\env\lib\site-packages\django\views\generic\edit.py", line 33, in get_form
return form_class(**self.get_form_kwargs())
TypeError: __init__() got an unexpected keyword argument 'us'
[06/Oct/2018 15:18:41] "GET /deals/dealAdd HTTP/1.1" 500 91563
my form
class dealForm(forms.ModelForm):
class Meta:
model=deals
fields= '__all__'
widgets={
'refno':forms.TextInput(attrs={'class':'input-sm form-
control ember-view ember-text-field'}),
'status':forms.Select(choices=stat,attrs={'class':'btn btn-deals'}),
'transaction_price':forms.TextInput(attrs={'class':'input-sm form-
control ember-view ember-text-field'}),
'estimated_closing_date':forms.TextInput(attrs={'class':'input-sm
form-control ember-view ember-text-field'}),
Maybe it's because of the order.
Your CreateView call get_context_data first before get_form_kwargs. It means it 'pop' your 'us' before it updated it.
Just change usr=kwargs.pop('us', None) to avoid error or use try/except for it.

'dict' object has no attribute 'filter' in django

I have created a class based view
class MyLibrary(generic.DetailView):
context_object_name = 'data'
def get_template_names(self):
request = self.request
template_name = 'my_library.html'
return [template_name]
def get_queryset(self):
request = self.request
user = request.user
context = {}
mainData = []
userIssuedBooks = BooksIssued.objects.filter(user=user)
print(userIssuedBooks)
if user.is_authenticated():
context['issuedBooks'] = userIssuedBooks
return context
I am getting following error when the view is getting called
Internal Server Error: /mylibrary/1/admin
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\django\core\handlers\base.py", line 149,
in get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python34\lib\site-packages\django\core\handlers\base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python34\lib\site-packages\django\contrib\auth\decorators.py", line 2
3, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Python34\lib\site-packages\django\views\generic\base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Python34\lib\site-packages\django\views\generic\base.py", line 88, in
dispatch
return handler(request, *args, **kwargs)
File "C:\Python34\lib\site-packages\django\views\generic\detail.py", line 117,
in get
self.object = self.get_object()
File "C:\Python34\lib\site-packages\django\views\generic\detail.py", line 38,
in get_object
queryset = queryset.filter(pk=pk)
AttributeError: 'dict' object has no attribute 'filter'
I have no clue why this error is getting generated. Can someone help to find what is wrong here?
In django DetailView, get_queryset expects user to return a queryset(as the name implies) but you returned a dict context. You need to do your current stuff in get_context_data instead.
Django doc about adding extra context.

BaseDeleteView throws AttributeError (render_to_response missing)

I try to implement a view based on BaseDeleteView for a website that acts as a frontend to an REST backend. Both sides communicate over HTTP requests. What I want to achieve is that I send a GET request to an activation URI (send per email after registration). Inside this view I first send a HTTP request to a backend, and then delete the activation object from the database of the frontend. I don't want to have a confirmation page, so DeleteView is not possible.
class ActivationView(BaseDeleteView):
success_url = "/activation/success/"
def get_object(self, queryset=None):
uuid = self.kwargs['uuid']
try:
obj = AccountRegistration.objects.get(uuid=uuid)
except ObjectDoesNotExist:
raise Http404('Registration not found.')
return obj
def delete(self, request, *args, **kwargs):
obj = self.get_obj()
if obj.expire_date < datetime.now():
obj.delete()
raise Http404('Registration expired.')
# send a http request to the backend
t = Transaction('/activate/%s/' % obj.account_name)
t.emit()
# delete the object
obj.delete()
# and redirect the request
return HttpResponseRedirect(self.get_success_url())
My urls.py looks like that:
url(r'^activate/(?P<uuid>\w+)/$',
ActivationView.as_view(), name="account-activate"),
But I get the following error:
Traceback (most recent call last):
File "/home/crito/.pythonbrew/venvs/Python-2.7.2/thirty-web/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 68, in __call__
return self.application(environ, start_response)
File "/home/crito/.pythonbrew/venvs/Python-2.7.2/thirty-web/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 272, in __call__
response = self.get_response(request)
File "/home/crito/.pythonbrew/venvs/Python-2.7.2/thirty-web/lib/python2.7/site-packages/django/core/handlers/base.py", line 169, in get_response
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
File "/home/crito/.pythonbrew/venvs/Python-2.7.2/thirty-web/lib/python2.7/site-packages/django/core/handlers/base.py", line 203, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File "/home/crito/.pythonbrew/venvs/Python-2.7.2/thirty-web/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/home/crito/.pythonbrew/venvs/Python-2.7.2/thirty-web/lib/python2.7/site-packages/django/views/generic/base.py", line 47, in view
return self.dispatch(request, *args, **kwargs)
File "/home/crito/.pythonbrew/venvs/Python-2.7.2/thirty-web/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in dispatch
return handler(request, *args, **kwargs)
File "/home/crito/.pythonbrew/venvs/Python-2.7.2/thirty-web/lib/python2.7/site-packages/django/views/generic/detail.py", line 100, in get
return self.render_to_response(context)
AttributeError: 'ActivationView' object has no attribute 'render_to_response'
In my eyes it shouldn't even call render_to_response. Any ideas?
If you want to leave out the confirmation page, just call your DeleteView directly with POST. This is most desirable as the deletion of an object should be protected by csrf.
You've inherited from BaseDeleteView, which as the documentation states, doesn't include the TemplateResponseMixin - ie all the bits that are to do with rendering a response.
Inherit from DeleteView instead.