Django on Pycharm: ImproperlyConfigured with DJANGO_SETTINGS_MODULE - django

I am trying to use Pycharm Community Edition to improve on my code in my Django application, but I cannot run all of my Django code that I'd like. I keep getting this traceback...
Traceback (most recent call last):
File "C:/Users/Jaysp_000/firstSite/PROJECTone/blog_static/views.py", line 1, in <module>
from django.views.decorators.csrf import csrf_exempt
File "C:\Python34\lib\site-packages\django\views\decorators\csrf.py", line 3, in <module>
from django.middleware.csrf import CsrfViewMiddleware, get_token
File "C:\Python34\lib\site-packages\django\middleware\csrf.py", line 14, in <module>
from django.utils.cache import patch_vary_headers
File "C:\Python34\lib\site-packages\django\utils\cache.py", line 26, in <module>
from django.core.cache import caches
File "C:\Python34\lib\site-packages\django\core\cache\__init__.py", line 34, in <module>
if DEFAULT_CACHE_ALIAS not in settings.CACHES:
File "C:\Python34\lib\site-packages\django\conf\__init__.py", line 48, in __getattr__
self._setup(name)
File "C:\Python34\lib\site-packages\django\conf\__init__.py", line 42, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
This error seems to involve the django.views.decortors.csrf.csrf_exempt that I imported to my views.py file. I've tried other files, and they have given me no issues. There is something in particular about this import, but I don't know what.
from django.views.decortors.csrf import csrf_exempt
#csrf_exempt
def handle_hook(request):
from django.http import HttpResponse
from django.core.management import call_command
result = call_command('update_blog', verbosity = 0)
return HttpResponse(result)
The same kind of issue shows up when I am trying to run the code on the python shell (I use 3.4) and when I import django.http.request as request. I type in handle_hook(request), and I get the same kind of error.
Im being told that I must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings, but I haven't a clue on how to do that. I've looked around and I am not certain if those methods specifically speak to my issue. Any clues?

Go to the Run Menu, select Edit Configurations..., then select the run configuration for you tests.
Select the environment variables button. You'll see one existing variable, which is PYTHONUNBUFFERED
Under that add (for example) DJANGO_SETTINGS_MODULE=mysitename.settings

Related

How to fix "django ImproperlyConfigured exception: Requested setting, You must either define the environment variable DJANGO_SETTINGS_MODULE."

Our Django application uses Django Rest Framework, Oauth2 and double settings - one to develop and other to production, and a general one called base.py. The development.py is currently set up on manage.py file. We are also using django-cors-headers package.
This exception starts yesterday when I use ./manage.py runserver or another command. I tried to fix it. I read many posts from here (Stackoverflow) and in other websites, but I did not make it.
Could someone help me, please?
Traceback (most recent call last):
File "./manage.py", line 5, in <module>
from settings import base, development
File "/home/ijdev/Área de Trabalho/izio/izio-bank/settings/base.py", line 12, in <module>
from corsheaders.defaults import default_methods as cors_default_methods
File "/home/ijdev/Área de Trabalho/izio/Izioenv/lib/python3.7/site-packages/corsheaders/defaults.py", line 14, in <module>
CORS_ALLOW_HEADERS = getattr(settings, 'CORS_ALLOW_HEADERS', default_headers)
File "/home/ijdev/Área de Trabalho/izio/Izioenv/lib/python3.7/site-packages/django/conf/__init__.py", line 79, in __getattr__
self._setup(name)
File "/home/ijdev/Área de Trabalho/izio/Izioenv/lib/python3.7/site-packages/django/conf/__init__.py", line 64, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting CORS_ALLOW_HEADERS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
In your base settings you have
from corsheaders.defaults import default_methods as cors_default_methods
This causes a circular import because corsheaders tries to import settings.
To solve the problem, remove the import from settings.

ImportError: cannot import name routes

I am doing Miguel Grinberg's tutorial on Flask. I am having a strange issue: before, this wasn't happening, but now it is. When I try to run flask shell or simply run my application, I receive the following error:
NoAppException: While importing "app.microblog", an ImportError was raised:
Traceback (most recent call last):
File "c:\projects\blog\virtualenv\lib\site-packages\flask\cli.py", line 235, in locate_app
__import__(module_name)
File "c:\Projects\Blog\app\__init__.py", line 14, in <module>
from app import routes, models
File "app.py", line 11, in <module>
ImportError: cannot import name routes
I thought it might be a circular dependency problem, but that didn't seem to be the case. I've tried searching all over for the answre but can't seem to figure it out.
Thanks for your help.
It seems you are importing the routes from app module within app module.. If you can share some more snippet, that would be helpful in understanding the problem.
But it seems,
from app import routes, models
File "app.py", line 11, in <module>
ImportError: cannot import name routes
In these lines, it says the exception is occuring in from app import routes, models line which is line 11 of app.py file.
So you are just importing the app module within app module.
I think you shouldn't import like the way you do already. Instead use the following:
import app
...
...
...
#app.routes('/something', methods=['DESIRED_METHODS']
def your_function():
pass

How do you confirm django is using memcached?

I have a python django webserver that I am trying to use memcached to make it faster.
I have downloaded and installed memcached and started it a user called virtual as follows:
/usr/local/bin/memcached -u virtual &
on the django setting.py, I have put the memcached server as this:
MEMCACHE_HOSTS = ['192.168.101.1:11211']
I can do telnet 192.168.101.1 11211 and stats, I do see some statistics there etc.
How do I really know if my django server utilizing the memcached? Is there directory that I can look at or some files to confirm?
Thank you for any insight.
content of manage.py:
#!/usr/bin/env python
import os
import sys
from django.core.management import execute_from_command_line
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
from the command line:
phthon
from django.core.management import execute_from_command_line
and when I do this:
from django.core.cache import cache
I get these errors:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib64/python2.6/site-packages/django/core/cache/__init__.py", line 69, in <module>
if DEFAULT_CACHE_ALIAS not in settings.CACHES:
File "/usr/local/lib64/python2.6/site-packages/django/conf/__init__.py", line 54, in __getattr__
self._setup(name)
File "/usr/local/lib64/python2.6/site-packages/django/conf/__init__.py", line 47, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
You can test cache in Django's shell (python manage.py shell):
>>> from django.core.cache import cache
>>> cache.set('foo', 'bar', 600)
>>> cache.get('foo')
'bar'
If cache.get() returns the set value it means that cache is working as it should. Otherwise it will return None.
An other option is to start memcached with $ memcached -vv, since it will log all the cache accesses to the terminal. Or alternatively you can install monitoring tool for memcached (i.e. memcache-top) and check that something is happening in memcached while using your app.

Export django settings to my python file

I am trying to make logparser.py in django project which parses the data coming from different servers.
And on running the command on terminal :
$ python logparser.py
This error is coming :
Traceback (most recent call last):
File "logparser.py", line 13, in <module>
SMTP_CONF = settings.SMTP_CONF
File "/home/arya/.virtualenv/Devel/.virtualenvs/hu/local/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__
self._setup(name)
File "/home/arya/.virtualenv/Devel/.virtualenvs/hu/local/lib/python2.7/site-packages/django/conf/__init__.py", line 48, in _setup
self._wrapped = Settings(settings_module)
File "/home/arya/.virtualenv/Devel/.virtualenvs/hu/local/lib/python2.7/site-packages/django/conf/__init__.py", line 134, in __init__
raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'hma.settings' (Is it on sys.path?): No module named hma.settings
my logparser.py contains:
import re
import os
import fnmatch
import gzip
import bz2
from collections import defaultdict
from django.core.mail import send_mail
from django.core.mail.backends import smtp
import smtplib
from email.mime.text import MIMEText
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hma.settings")
from django.conf import settings
SMTP_CONF = settings.SMTP_CONF
def send_email(self,fromaddress,toaddresses,content,subject):
smtp_server = SMTP_CONF["SERVER"]
smtp_username = SMTP_CONF["USERNAME"]
smtp_password = SMTP_CONF["PASSWORD"]
smtp_port = SMTP_CONF["PORT"]
msg = MIMEText(content, 'html', _charset='utf-8')
msg['Subject'] ='Alert message for bad and internal server error'
msg['From'] = fromaddress
msg['To'] = toaddresses
server = smtplib.SMTP(smtp_server,smtp_port)
server.starttls()
server.login(smtp_username,smtp_password)
server.send_mail(fromaddress,toaddresses,msg.as_string())
server.quit()
return True
I know I am doing wrong something with command [python manage.py], but i need to run like this. Any solution for this exporting django settings to separate python file??
Well, This is the exact Usecase why Django provided an ability to create custom commands. You can use all the features of django, in your script, Its like your script will be running inside a Django Container. Here is the Documentation https://docs.djangoproject.com/en/dev/howto/custom-management-commands/.
In case you don't want to use custom management commands though there is also a simple way to run your code within Django's context. Simply put the following at the beginning of your python file, you want to run:
from django.conf import settings
from django.core import management
management.setup_environ(settings)

Django 1.4 not recognizing my app

I am using django 1.4, and the app.module name does not seem to be working as expected for me. My settings.py has the app included as "survey.surveys".
Here is the django shell dump for an import I attempted through a preexisting file. The error says No module named ....
from survey.surveys.views.db import mobile_survey1
Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/pjain/dev/survey/survey/surveys/views/db.py", line 6, in <module>
from survey.surveys.models import Survey, Section, Question, Option
File "/home/pjain/dev/survey/survey/surveys/views/survey.py", line 7, in <module>
from survey.surveys.models import Survey, Section, Question, Option
ImportError: No module named surveys.models
However, when I copied and pasted the exact import which breaks, it imports fine in the shell.
from survey.surveys.models import Survey, Section, Question, Option
How can I fix this import in my project?