Not naive datetime (tzinfo is already set) - django

I use django celery in my django app and I'm experiencing this error:
ValueError: Not naive datetime (tzinfo is already set) in djcelery.utils in make_aware
How to fix this?

I think it's a bug from django-celery when they upgrade their version. But by the way, put this in your init.py where your settings.py located.
# Patch the djcelery/snapshot cause it's broken
import datetime
from django.utils.timezone import is_aware
import djcelery.snapshot
orig_maybe_make_aware = djcelery.snapshot.maybe_make_aware
def new_maybe_make_aware(value):
if isinstance(value, datetime.datetime) and is_aware(value):
return value
return orig_maybe_make_aware(value)
djcelery.snapshot.maybe_make_aware = new_maybe_make_aware

Related

Problem to run a check in my database in django

I have created a model called Certs, the models is registered and it is showing in the admin page, however I am trying to call it to run a check and try to make a task, but I am getting the error: No module named 'ships',
This is the structure of my project (note I am writing the code in reminders.py):
And here my code:
from django.core.mail import send_mail
from ships.models import Certs
from datetime import datetime, timedelta
b = Certs.objects.count()
def notifications():
for dates in range(b):
if Certs.exp_date[b] <= datetime.datetime.now() - timedelta(days=30):
send_mail(subject='Test',message='This is a reminder where you will be reminded about expiring certifications', recipient_list=['info#intermaritime.org'])
Thank you very much
Add the ships module to your INSTALLED section of settings.py

Get Timezone to take effect

I am going through the Django tutorial.
I thought the TIME_ZONE in settings.py was of form 'UTC-5', but it isn't.
I replaced it with 'America/Chicago'
However, when I do:
python manage.py shell
from django.utils import timezone
timezone.now()
I get 'UTC'
How do I get the timezone to take effect?
It can be confusing. If you run the code below, you will see that it is set, but it won't output as you expect:
from django.utils import timezone
timezone.get_current_timezone() # Should be 'America/Chicago'
timezone.now() # should show UTC
If you want it to output in the shell with your set timezone, use timezone.localtime()
from django.utils import timezone
timezone.localtime()

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?

How to modify dumpdata generated django json fixture prior to loading into database

I am a relative django newbie. I have a json fixture for the django.contrib.auth.user objects from an existing database that I want to load into my test app. The specific field I want to modify are all the Datetime Fields that do not have UTC offsets built into them. I want to add these UTC offsets using a python script.
I am using the django deserializer but am having no luck and get an error during the deserialization.
File "add_utc_offset_to_fixture.py", line 24, in <module>
for obj in serializers.deserialize("json", json_fixture):
File "/Users/hari/.virtualenvs/bsc2/lib/python2.7/site-packages/django/core/serializers/json.py", line 47, in Deserializer
raise DeserializationError(e)
django.core.serializers.base.DeserializationError: No module named Image
How do I get around this deserialization error, or alternatively how do I modify this fixtures before loading into the database.
I looked into my fixtures and also into the json.py deserializer and do not understand why it needs a module called Image.
My code
# This program reads in a json fixture with naive Datetime field and converts it into a UTC aware Datetime field
# For Documentation on this see https://docs.djangoproject.com/en/dev/topics/i18n/timezones/#time-zones-migration-guide
import sys,os
# Sets the django settings module
dir_two_steps_up_from_me = os.path.join(os.path.split(os.path.dirname(os.path.abspath(__file__)))[-2])
print "Adding %s to sys.path" % dir_two_steps_up_from_me
sys.path.append(dir_two_steps_up_from_me)
from bsc2 import settings
from django.core.management import setup_environ
# Deprecated but still using
setup_environ(settings)
from django.core import serializers
from django.contrib.auth.models import User
json_fixture = None
try:
json_fixture = open(sys.argv[1],"rb")
except IndexError,IOError:
print "Please give json fixture"
exit()
for obj in serializers.deserialize("json", json_fixture):
# Getting deserialization error when this executes
print obj.first_name
# TODO Code to change naive time in last_login to UTC time

Django app_cache_ready method returns True on Dev and False on production

I can't figure out what can be the reason.
On my dev machine the exactly same django project runs properly, while on production in the custom middleware code app_cache_ready() method always returns False. If I ignore and bypass it cache.set does not cache the object.
My dev environment uses runserver to launch the server, while the production uses Apache and mod_wsgi with virtualhost directives.
Does anyone have a clue what might be the problem? I have already spent couple of hours with no success.
Thanks in advance
Below is the simplified code that fails to cache again:
from django.conf import settings
from django.contrib.sites.models import Site
from django.http import HttpResponseRedirect, Http404
from django.core.cache import cache
from django.db.models.loading import app_cache_ready
from django.utils.cache import patch_vary_headers
class MyMiddleware(object):
def process_request(self, request):
key='kuku'
val=cache.get(key)
if not val:
logger.warn('Cached key is not available')
cache.set(key,5)
else:
logger.warn('Cached key is %s' % str(val))
With subsequent calls I see always Cached key is not available.