Pytorch Model causing 500 server error in Django App - django

This is My Django project Directory, and in the "bills" app, I am trying to import my YOLOV5 pre-trained custom model (which works fine on its own).
So Views.py :
def crop(request):
model = torch.hub.load('../yolov5-master', 'custom', path='../best.pt', force_reload=True)
return render(request, '../templates/results.html')
This is causing my app to return a 500 server error when hitting that URL; I know the model is causing it because if I comment out that first line
#model = torch.hub.load('../yolov5-master', 'custom', path='../best.pt', force_reload=True)
Then the page shows fine.
I looked up many articles on how to load a Pytorch model into Django and it seems I am doing it right, can you please help me figure out what's the problem ?

I think the issue is related to path. You can try this in views.py:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "yourappname.settings")
django.setup()
from django.conf import settings
model = torch.hub.load('../yolov5-master', 'custom', path=os.path.join(settings.MEDIA_ROOT, 'best.pt'), force_reload=True)
In your settings.py, you will first need to configure your MEDIA_ROOT path like this:
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploaded_media')

Related

Django REST API Generics displaying improperly

Currently using a REST API and the generic views CreateUpdateDestroy, and my admin display GUI looks like this :
All the sources online that I've followed, tutorials etc get a generic view which looks much nicer.
Here is my views.py:
from rest_framework import generics
from models import Results
from serializers import ResulutsSerializer
class ResultsList(generics.ListAPIView):
queryset = Results.objects.all()
serializer_class = ResultsSerializer
class ResultsDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Results.objects.all()
serializer_class = ResultsSerializer
and urls.py:
from django.urls import path
from main import views
urlpatterns = [
path('results/', views.ResultsList.as_view()),
path('<int:pk>/', views.ResultsDetails.as_view())
]
what am I doing wrong?
It looks like you need to collect your app assets:
$ python manage.py collectstatic
# You can provide option: --settings=<your-settings-file> if you're using custom settings which is not default in manage.py
You will need to configure staticfiles settings in your Django settings module if not already configured – e.g. settings.py. Please follow documentation at:
https://docs.djangoproject.com/en/2.0/howto/static-files/
https://docs.djangoproject.com/en/2.0/ref/contrib/staticfiles/
If you are developing locally:
You should set DEBUG=True in your Django Settings Module (i.e. normally settings.py)

Timezone It works locally but not in pythonanywhere (DJango)

I have a queryset to list today's sales
from django.utils import timezone
class VentaToday(ListView):
queryset = Venta.objects.filter(fecha=timezone.now()).order_by('-id')
template_name = 'venta/venta_today.html'
In local, this works correctly but in production (Pythonanywhere) the sales of the previous day keep appearing. To fix it, I have to go to the pythonanywhere panel and click on the ** reload ** button to solve the problem.
I changed the server time:
Image of server time
Configuration of the django project:
LANGUAGE_CODE = 'es-pe'
TIME_ZONE = 'America/Lima'
USE_I18N = True
USE_L10N = True
USE_TZ = True
Is it a server cache problem? or something am I doing wrong?
UPDATE
config WSGI:
# +++++++++++ DJANGO +++++++++++
# To use your own django app use code like this:
import os
import sys
os.environ["TZ"] = "America/Lima"
#
## assuming your django settings file is at '/home/dnicosventas/mysite/mysite/settings.py'
## and your manage.py is is at '/home/dnicosventas/mysite/manage.py'
path = '/home/dnicosventas/dnicos-ventas'
if path not in sys.path:
sys.path.append(path)
#
os.environ['DJANGO_SETTINGS_MODULE'] = 'DnicosVentas.settings'
#
## then, for django >=1.5:
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
## or, for older django <=1.4
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
and my console:
export TZ="/usr/share/zoneinfo/America/Lima"
Even so, after 12 a.m., yesterday's sales keep appearing until I click on the reload button in the pythonanywhere panel.
Views.py:
class VentaToday(ListView):
today = datetime.now(pytz.timezone('America/Lima'))
queryset = Venta.objects.filter(fecha=today).order_by('-id')
template_name = 'venta/venta_today.html'
Image of the reload button
Solution by Giles Thomas:
class VentaToday(ListView):
template_name = 'venta/venta_today.html'
def get_queryset(self):
return Venta.objects.filter(fecha=datetime.now(pytz.timezone('America/Lima'))).order_by('-id')
TLDR: I had the same issue. I fixed it by changing TIME_ZONE='' to TIME_ZONE='UTC', in the settings.py file in project folder of pythonanywhere.
Python by default uses pytz.timezone(settings.TIME_ZONE), to initiate the time zone of the webapp, and since by default pythonanywhere doesnt initiate this variable, leaving it to the end user to do it, as per their requirements. So initiate your TIME_ZONE, as per your needs, which may do the trick.
You could also try looking in your project log files, for more information on this.

Django REST views: return images without models

I am completely new to Django REST, and I have been wasting time googling for a way to accomplish something that does not seem to be excessively difficult.
I want to define a view using the Django predefined classes for views. This view should return an image (given its name), so a URL like this would return the image example.png:
http://localhost:8000/api/v1/image/example.png
However I do not want this image to be stored in a model (it would be stored in the server as a png file). The class rest_framework.generics.RetrieveAPIView seems to suit my needs, as I can set permissions and authentication classes to restrict the access to the images, but I cannot figure out how to set the queryset if I do not have a model with my images.
Any ideas on this? Thanks and forgive my ignorance.
If I understand well, you want to check permissions before allowing access to an image.
I do not think Generic Views is the good path for you as you are not tied to a db model:
The generic views provided by REST framework allow you to quickly
build API views that map closely to your database models.
A better path could be Class Based Views, as suggested by Ivan Semochkin, something like:
class GetMyImage(APIView):
authentication_classes = (...,)
permission_classes = (...,)
def get(self, request, format=None):
with open('file path...') as fh:
return HttpResponse(fh.read(), content_type='content/image')
Of course do not forget your urls.py:
urlpatterns = [
url(r'^image/example.png$', views.GetMyImage.as_view()),
]
You can use HttpResponse to return simple json data. Please override get method in your view class.
import json
from django.http import HttpResponse
response_data = {}
response_data['image'] = 'http://localhost:8000/api/v1/image/example.png'
return HttpResponse(json.dumps(response_data), content_type="application/json")
Django will store all your media files where you have specified your root media folder to be. It will also serve them from the specified root media url.
In your settings add;
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
Images files will be then available at 'http://localhost:8000/media/' if in your root configuration urls you add:
urlpatterns = [
url(r'^api/v1/', include('api.urls', namespace='api')),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Remember to import your configuration settings and the static method:
from django.conf import settings
from django.conf.urls.static import static

enable a model on Django Admin on Dreamhost

Hi I've created a new app (Paginas) but I cannot see inside the admin page. I've added 'paginas' to INSTALLED_APP. My admin.py is
# coding=utf-8
from django.contrib import admin
from .models import Pagina
class PaginaAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("titulo",)}
list_display = ('titulo' , 'contenido')
class Media:
js = ('/layout/grappelli/tinymce/jscripts/tiny_mce/tiny_mce.js','/layout/grappelli/tinymce_setup/tinymce_setup.js')
admin.site.register(Pagina,PaginaAdmin)
I am using passenger_wsgi.py file, I've touched tmp/restart.txt file, I've killed python process
I don't know what else can I do
The project you can see it on github https://github.com/totechess/paralisis_cerebral
What kind of error do you get when you go to your site yoursite.com/admin/
Did you add admin to INSTALLED_APPS? Note the S
....
'django.contrib.admin',
....
Perhaps your urls.py are not updated properly? What is the error?

Django admin: Can't add app to admin

I have installed Django on my host (I use their install version 1.1.1), all is working fine.
I have created some apps and they are registered in my settings.py (I can verify this works when i visit the site, the app shows up).
In the folder of this app i have created admin.py with the following content:
from progmaticnet.page.models import Page, PageContent
from django.contrib import admin
class PageContentInline( admin.StackedInline ):
model = PageContent
extra = 1
max_num = 1
class PageAdmin( admin.ModelAdmin ):
inlines = [ PageContentInline ]
class Media:
#js = ('/site_media/js/tinymce/jscripts/tiny_mce/tiny_mce.js', '/site_media/js/tinymce/textarea.js')
admin.site.register( Page, PageAdmin )
But my app doesn't show up in the admin... It is said in the documentation that you'll need to restart the server, although i can't do that (runs on apache), i have a dispatch.fcgi with this content:
#!/usr/bin/python
import sys, os
project_sys="/home/progmati/public_html"
#add a custom python path
sys.path.insert(0, project_sys)
# set the DJANGO_SETTINGS_MODULE environment variable
os.environ['DJANGO_SETTINGS_MODULE'] = 'progmaticnet.settings'
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded")
I have killed the process and started it anew but with no avail...
Does anybody know what to do about it?
Thanks
Why is the js declaration commented out in your Media class? That looks like it'll be an invalid class definition as a result (class definitions can't be entirely empty). Try uncommenting it, or adding pass below the commented out line, like this:
class Media:
#js = ('/site_media/js/tinymce/jscripts/tiny_mce/tiny_mce.js', '/site_media/js/tinymce/textarea.js')
pass