Timezone It works locally but not in pythonanywhere (DJango) - 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.

Related

Pytorch Model causing 500 server error in Django App

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

Timezone is UTC infact of changing it in settings.py file

My app is showing the timezone.now() as UTC time when I see it in Heroku scheduler. Also I built a custom manage.py command to test it but it still shows UTC time.
Here is my settings.py
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Kolkata'
USE_I18N = True
USE_L10N = True
USE_TZ = True
Here is my personalied manage.py command
managemet/commaands/abhiwaqt.py
from django.core.management.base import BaseCommand, CommandError
from django.apps import apps
from Directory.utils import *
class Command(BaseCommand):
help="Refresh models and its fields."
def handle(self,*args, **options):
try:
print(timezone.now())
except:
raise CommandError("Something went wrong")
Infact of setting TIME_ZONE='Asia/Kolkata' I am getting this issue.
It is probably good practice to keep your back end using UTC so everything is uniform and handles daylight savings and you simply handle the changes when displaying to the user in templates or views. If you want timezone support (since it is disabled by default) use the setting USE_TZ = True. Take a look at the docs for more in depth explanation on this topic.enter link description here

Date time and Date format localization with Django Rest Framework

I am creating API with DRF and Django 1.8 using python 2.7.x and Postgres 9.4. API is consumed by front end using AngularJS. I need to do time conversion to different time zones as per user set timezone. I tried creating a middleware as shown below -
import pytz
from django.utils import timezone
from django.conf import settings
class TimezoneMiddleware(object):
def process_request(self, request):
request.session["user_pref_timezone"] = "Europe/Paris"
tzname = request.session.get('user_pref_timezone')
settings.DATE_FORMAT = request.session.get('date')
settings.TIME_FORMAT = request.session.get('time')
if tzname:
timezone.activate(pytz.timezone(tzname))
else:
timezone.deactivate()
And added it to settings.py under MIDDLEWARE_CLASSES as
'core.middleware.timezone.TimezoneMiddleware',
in settings.py I have added ,
USE_TZ = True
import pytz
TIMEZONES = ( (tz, tz) for tz in pytz.common_timezones )
still I can not see my time converted from UTC to specific country timezone. Am I missing something?

Django Lettuce built-in server 500 response

I am running the Lettuce built-in server to test that it returns a given reponse however, it shows a 500 response.
My features file:
Feature: home page loads
Scenario: Check that home page loads with header
Given I access the home url
then the home page should load with the title "Movies currently showing"
My steps file:
#step(u'Given I access the home url')
def given_i_access_the_home_url(step):
world.response = world.browser.get(django_url('/'))
sleep(10)
#step(u'then the home page should load with the title "([^"]*)"')
def then_the_home_page_should_load_with_the_title_group1(step, group1):
assert group1 in world.response
My Terrains file:
from django.core.management import call_command
from django.test.simple import DjangoTestSuiteRunner
from lettuce import before, after, world
from logging import getLogger
from selenium import webdriver
try:
from south.management.commands import patch_for_test_db_setup
except:
pass
logger = getLogger(__name__)
logger.info("Loading the terrain file...")
#before.runserver
def setup_database(actual_server):
'''
This will setup your database, sync it, and run migrations if you are using South.
It does this before the Test Django server is set up.
'''
logger.info("Setting up a test database...")
# Uncomment if you are using South
# patch_for_test_db_setup()
world.test_runner = DjangoTestSuiteRunner(interactive=False)
DjangoTestSuiteRunner.setup_test_environment(world.test_runner)
world.created_db = DjangoTestSuiteRunner.setup_databases(world.test_runner)
call_command('syncdb', interactive=False, verbosity=0)
# Uncomment if you are using South
# call_command('migrate', interactive=False, verbosity=0)
#after.runserver
def teardown_database(actual_server):
'''
This will destroy your test database after all of your tests have executed.
'''
logger.info("Destroying the test database ...")
DjangoTestSuiteRunner.teardown_databases(world.test_runner, world.created_db)
#before.all
def setup_browser():
world.browser = webdriver.Firefox()
#after.all
def teardown_browser(total):
world.browser.quit()
What could be the problem with the server, why a 500 response error?
I managed to find what the problem is, the migrations were not running on syncdb

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