Negative indexing is not supported in django - django

I am trying to upload image and show the same in my site but instead i am getting this error
my current django-mptt version is 0.5.1
views.py-
def home(request):
print('here you go ')
images=[]
images=image_classification.objects.all()
url=images[len(images)-1].pic.url
return render(request,'home.html',{'print':'everything is ok','image':url})
#handles uploaded images
def uploadImage(request):
print('image handling ')
img= request.FILES['image']
image=image_classification(pic=img)
image.save()
return HttpResponseRedirect('/')
inside models.py
from django.db import models
class image_classification(models.Model):
pic=models.ImageField(upload_to='images')
and the error i am facing
Traceback (most recent call last):
File "C:\Users\prasa\Desktop\Pytorch-Django\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\prasa\Desktop\Pytorch-Django\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\prasa\Desktop\Pytorch-Django\MainApp\ImageClassifier\views.py", line 10, in home
url=images[len(images)-1].pic.url
File "C:\Users\prasa\Desktop\Pytorch-Django\venv\Lib\site-packages\django\db\models\query.py", line 425, in __getitem__
raise ValueError("Negative indexing is not supported.")
Exception Type: ValueError at /
Exception Value: Negative indexing is not supported.

images is empty (the queryset).you could handle if by using IF statment.
def home(request):
print('here you go ')
images=[]
images=image_classification.objects.all()
if len(imgaes) > 0:
url=images[len(images)-1].pic.url
else:
url="place holder image url"
return render(request,'home.html',{'print':'everything is ok','image':url})

Related

I'm trying to create a Web App using Django, I've encountered unknown 500 errors I can't debug

This is the error that occurs, it seems to happen when I request a .html file from my templates folder but for some unknown reason to me it fails to show and throws these errors I haven't been able to figure out for a couple days.
If additional information is needed I will provide it thank you to anyone who assists
Traceback (most recent call last):
File "C:\Users\uknow\Desktop\Coding\GoFishFarms\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\uknow\Desktop\Coding\GoFishFarms\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\uknow\Desktop\Coding\GoFishFarms\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\uknow\Desktop\Coding\GoFishFarms\pages\views.py", line 5, in index
return render(request, 'index.html')
File "C:\Users\uknow\Desktop\Coding\GoFishFarms\venv\lib\site-packages\django\shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Users\uknow\Desktop\Coding\GoFishFarms\venv\lib\site-packages\django\template\loader.py", line 61, in render_to_string
template = get_template(template_name, using=using)
File "C:\Users\uknow\Desktop\Coding\GoFishFarms\venv\lib\site-packages\django\template\loader.py", line 19, in get_template
raise TemplateDoesNotExist(template_name, chain=chain)
django.template.exceptions.TemplateDoesNotExist: index.html
[25/Jul/2020 13:29:40] "GET / HTTP/1.1" 500 82139
Views.py
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request, 'index.html')
def about(request):
return render(request, 'about.html')
Directory Structure
you correctly set up the directory structure (best practice) and now when Django 'sets up' the main templates folder it will look like this templates/, templates/pages/index.html, templates/pages/about.html. render() will automatically get the templates/ part so you have to give it the rest - render(request, 'pages/index.html')
IMPORTANT
Remember to add pages app to INSTALLED_APPS in settings.py
INSTALLED_APPS = [
...
'pages',
...
]
otherwise Django will not attach pages to your templates folder

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'],
)

AttributeError: 'bytes' object has no attribute

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.

Validate each value of an ArrayField of emails in Django

I am using PostgreSQL with Django and am trying to use ArrayField(models.EmailField(max_length=200)). But I am ending up with an 500 error code(TypeError) when giving invalid email address.
How can I validate each email in the ArrayField. I have tried writing validate method in both serializer and models. But nothing helped. What is the right way to validate ArrayFields? I am using Django 2.1 and Python 3.6
The traceback of the error is given below...please have a look
models.py
billing_emails = ArrayField(models.EmailField(max_length=200))
company = models.OneToOneField(Company, on_delete=models.CASCADE)
Traceback
Traceback (most recent call last):
File "/home/user/.local/share/virtualenvs/backend-Amy45Zrz/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/user/.local/share/virtualenvs/backend-Amy45Zrz/lib/python3.6/site-packages/django/core/handlers/base.py", line 156, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/user/.local/share/virtualenvs/backend-Amy45Zrz/lib/python3.6/site-packages/django/core/handlers/base.py", line 154, in _get_response
response = response.render()
File "/home/user/.local/share/virtualenvs/backend-Amy45Zrz/lib/python3.6/site-packages/django/template/response.py", line 106, in render
self.content = self.rendered_content
File "/home/user/.local/share/virtualenvs/backend-Amy45Zrz/lib/python3.6/site-packages/rest_framework/response.py", line 72, in rendered_content
ret = renderer.render(self.data, accepted_media_type, context)
File "/home/user/.local/share/virtualenvs/backend-Amy45Zrz/lib/python3.6/site-packages/djangorestframework_camel_case/render.py", line 8, in render
return super(CamelCaseJSONRenderer, self).render(camelize(data), *args,
File "/home/user/.local/share/virtualenvs/backend-Amy45Zrz/lib/python3.6/site-packages/djangorestframework_camel_case/util.py", line 17, in camelize
new_dict[new_key] = camelize(value)
File "/home/user/.local/share/virtualenvs/backend-Amy45Zrz/lib/python3.6/site-packages/djangorestframework_camel_case/util.py", line 16, in camelize
new_key = re.sub(r"[a-z]_[a-z]", underscoreToCamel, key)
File "/home/user/.local/share/virtualenvs/backend-Amy45Zrz/lib/python3.6/re.py", line 191, in sub
return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object
Thanks in advance.
If you are using Forms, use Form or Serializer, you can use the clean_<attribute_name> method to validate the data. For example:
from django.core.validators import email_re
from django.core.exceptions import ValidationError
class YourForm(forms.ModelForm): # serializers.ModelSerializer
def clean_billing_emails(self):
data = self.cleaned_data['billing_emails']
for email in data:
if not email_re.match(email):
raise ValidationError('Invalid email {}'.format(email) # or raise serializers.ValidationError
return data
Also you can use model's clean method.
class YourModel(models.Model):
...
def clean(self):
try:
for email in self.billing_emails:
if not email_re.match(email):
raise ValidationError('Invalid email {}'.format(email)
except (TypeError, Exception) as e:
# log error
# handle error
def save(self, *args, **kwargs):
self.full_clean()
return super(YourModel, self).save(*args, **kwargs)

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.