PyLint failing for a number of Django imports - django

I am using PyLint,
pylint -e app/views.py
Gives me errors like
E: 3: No name 'shortcuts' in module 'django'
E: 7: No name 'db' in module 'django'
But passes for other django imports. Since it passes for other Django import Django is on my pythonpath.

I think I figured it out -- if you jump into a python session and actually try to import anything from django.db
from django.db import *
you'll get an error about DJANGO_SETTINGS_MODULE not being set. Setting the environment variable and pointing it to your settings.py like app.settings should fix the error for you.
When I tried this in an Eclipse/PyDev config I had to disable pylint, build, then re-enable pylint to finally clear out those errors.

Have you tried djangolint, which is a wrapper around Pylint with Django-specific settings?

Related

error with django.core.exceptions.ImproperlyConfigured: on Django 2.2.5

I know that this question has been asked before and I went through every possible answers given, and it still does not make it for me! I am running django 2.2.5 and python 3.7 on PyCharm.
My manage.py seems to be working fine. The issue is coming from my admin file, I believe I know but I do not know where the issue could be. I ran django-admin check in terminal, which also give me an error. My only file that raises an error is my admin.py, but I cannot understand why. I copied my admin.py file as well as the errors that I get when I write the commands on the terminal
from django.contrib import admin
from import_export.admin import ImportExportModelAdmin
from inventory1.templates.models import *
#admin.register(Item)
class ViewAdmin(ImportExportModelAdmin):
exclude= ('id',)
And when I execute it, I get the error:
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
Now, I am sure this is related too. When I try django-admin check, I get:
django.core.exceptions.ImproperlyConfigured: Requested setting TEMPLATES, but settings are not configured.
You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
From previous questions, this issue was coming from an issue with settings in the manage.py file. I am confident that this one is correct, I still add it just in case:
import os
import sys
if __name__ == '__main__':
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "inventory_management.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)

django-registration-redux falls with "Import error" exception

I have installed in my virtualenv django-reg.-redux
then i have added 'registration' app in INSTALLED_APPS,
but when i type python manage.py migrate
What package i have missed?stacktrace here
You need to manually update the admin.py file inside the registration app.
Open up registration\admin.py and then use the following import:
from django.contrib.sites.requests import RequestSite
instead of the wrong import:
from django.contrib.sites.models import RequestSite

Django ImportError for models.py

(Updating my question with more information.)
My django app is running fine on my dev server.
I have a view that pulls from the database using the below line that works fine:
from myapp.models import MyTable
However, if I add the above 'from/import' to another module (see below structure, it's the module named 'problem_module.py') I'm writing where I want to pull from the sqlite3 database, I get this error.
raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'myfolder.settings' (Is it on sys.path?): No module named myfolder.settings
I've read and tried various solutions recommended when people get this error, but I missing something because i'm unable to resolve it.
I'm using Django 1.4 and have the lay-out as recommended.
mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
wsgi.py
myapp/
__init__.py
models.py
admin.py
views.py
indevelopment/
__init__.py
problem_module.py
I figured out what was happening and why after going through the traceback carefully and looking at the django source code. Here is what happens.
When you run:
python manage.py runserver
the environment variable gets set properly assuming you already changed this small little file or just don't pay attention to it because django 1.4 automatically configures it for you.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
However, because this setting of os.environ is under a:
if __name__ = "__main__"
expression, it only gets run if call that file directly, as you do with:
python manage.py runserver
Otherwise, if you are running a file that needs that environment variable - say testing a module in Eclipse - , the os.environ needs to get set in another place (shell, etc).
All the that I got generally pointed to this but I needed the context.
But as a little adjustment (yes, not a good idea as it couples) on the source code you can also hardcode it in manually in/django/conf/__init__.py
Specifically to see where it happens, the change below works:
# in module: /django/conf/__init__.py
class LazySettings(LazyObject):
def _setup(self):
try:
# Comment out the call to os.environ and hardcode in your app settings
# settings_module = os.environ[ENVIRONMENT_VARIABLE]
# WARNING: bad practice to do this. ;.
settings_module = "myapp.settings"
Have you changed/set DJANGO_SETTINGS_MODULE?
Try export DJANGO_SETTINGS_MODULE=mysite.settings and start your dev server.
modify your manage.py:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
PyCharm sometimes override DJANGO_SETTINGS_MODULE to empty string. Try to debug your manage.py and see if it realy changes after setdefault() call.
If its not either change pycharm settings or use os.environ['DJANGO....']='my_settings'..
or hack files at .idea/. .idea/workspaed.xml contains
env name="DJANGO_SETTINGS_MODULE" value="" in this case

Calling a model's method from outside Django

I have a Django model with some static methods. I'd like to call the methods from outside the application (cronjob).
The model I have:
class Job(models.Job):
#Irrelevant information
#staticmethod
def methodIwantToCall():
#statements
I have the following python file that I'm using for the cron job:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from myapp.models import Job
Job.methodIwantToCall()
At first, I was having an error about DJANGO_SETTINGS_MODULE not being set and I fixed that, however, now I have the following error: No module named myapp.utils
I feel like I'm doing something that I'm not supposed to do. So how do I call that static method the way I want it to be called?
EDIT: It looks like the paths are getting messed up when I'm importing from outside Django. For example, I have an import in my models file, when I call the cron file it fails importing with the message ImportError: No module named myapp.utils even though it's working.
The proper solution is to create custom manage.py command.
Assuming your cron job code resides in the same directory as your settings file, use the following setup code at the beginning:
from django.core.management import setup_environ
import settings
setup_environ(settings)

How do you set DEBUG to True when running a Django test?

I'm currently running some Django tests and it looks that DEBUG=False by default. Is there a way to run a specific test where I can set DEBUG=True at the command line or in code?
For a specific test inside a test case, you can use the override_settings decorator:
from django.test.utils import override_settings
from django.conf import settings
class TestSomething(TestCase):
#override_settings(DEBUG=True)
def test_debug(self):
assert settings.DEBUG
Starting with Django 1.11 you can use --debug-mode to set the DEBUG setting to True prior to running tests.
The accepted answer didn't work for me. I use Selenium for testing, and setting #override_settings(DEBUG=True) makes the test browser always display 404 error on every page. And DEBUG=False does not show exception tracebacks. So I found a workaround.
The idea is to emulate DEBUG=True behaviour, using custom 500 handler and built-in django 500 error handler.
Add this to myapp.views:
import sys
from django import http
from django.views.debug import ExceptionReporter
def show_server_error(request):
"""
500 error handler to show Django default 500 template
with nice error information and traceback.
Useful in testing, if you can't set DEBUG=True.
Templates: `500.html`
Context: sys.exc_info() results
"""
exc_type, exc_value, exc_traceback = sys.exc_info()
error = ExceptionReporter(request, exc_type, exc_value, exc_traceback)
return http.HttpResponseServerError(error.get_traceback_html())
urls.py:
from django.conf import settings
if settings.TESTING_MODE:
# enable this handler only for testing,
# so that if DEBUG=False and we're not testing,
# the default handler is used
handler500 = 'myapp.views.show_server_error'
settings.py:
# detect testing mode
import sys
TESTING_MODE = 'test' in sys.argv
Now if any of your Selenium tests encounters 500 error, you'll see a nice error page with traceback and everything. If you run a normal non-testing environment, default 500 handler is used.
Inspired by:
Where in django is the default 500 traceback rendered so that I can use it to create my own logs?
django - how to detect test environment
Okay let's say you want to write tests for error testcase for which the urls are :-
urls.py
if settings.DEBUG:
urlpatterns += [
url(r'^404/$', page_not_found_view),
url(r'^500/$', my_custom_error_view),
url(r'^400/$', bad_request_view),
url(r'^403/$', permission_denied_view),
]
test_urls.py:-
from django.conf import settings
class ErroCodeUrl(TestCase):
def setUp(self):
settings.DEBUG = True
def test_400_error(self):
response = self.client.get('/400/')
self.assertEqual(response.status_code, 500)
Hope you got some idea!
Nothing worked for me except https://stackoverflow.com/a/1118271/5750078
Use Python 3.7
breakpoint()
method.
Works fine on pycharm
You can't see the results of DEBUG=True when running a unit test. The pages don't display anywhere. No browser.
Changing DEBUG has no effect, since the web pages (with the debugging output) are not visible anywhere.
If you want to see a debugging web page related to a failing unit test, then do this.
Drop your development database.
Rerun syncdb to build an empty development database.
Run the various loaddata scripts to rebuild the fixtures for that test in your development database.
Run the server and browse the page.
Now you can see the debug output.