In pycharm can I run every file for django? - python

I'm new to Django. My localhost site is running fine. Since I am using pycharm it is easy to run any file. I decided to run each file in my django project, and came across several errors, such as this one in my views.py:
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
Even though the site is running, what seems like properly, I'm seeing this message. What is causing this, and is it typical?

You cannot run each file present in your django project individual.
No matter those are file with .py extension. They depend on the django framework to get the project running.
The reason you might be seeing that error is because you might be using the attributes present in the settings.py file which in turn requires django to set the application running like starting the WSGI server, getting all the dependencies and the installed apps ready before you actually use anything.
Understand that Django is a Framework and it relies on many underlying components to actually work. Even thought you can technically run any file in any manner, you cannot start the application itself.
There are other ways to do it if you like to test the application like using django shell by python manage.py shell to check and test the application, which would be a better way of doing individual testing rather than running each file standalone.

You can run any individual python file in a Django Project with Django, but keep in mind that the settings for Django must be supplied. This is not a good practise to run individual file with Django but for debugging purposes you may use it (for example. to test a parser that you wrote with database access),
You have to configure the Django settings before you can do anything with Django on a single file.
from django.conf import settings
settings.configure()
def do_something_with_a_model():
# does something with a model
print "I am done!!"
Note that relative imports may break when running on single files.
(for example. imports like from .another_module import AnotherClass may break when working with single file.)

Related

How can run django tests in Pycharm Pro, getting ImproperlyConfigured and AppRegistryNotReady errors

I am having issues running django tests in PyCharm Pro.
I am able to run python manage.py runserver just fine.
I am able to migrate, makemigrations, manage.py test just fine. Actually, everything with manage.py runs as expected.
Whenever I run tests in PyCharm (by clicking the green run button), I get this error:
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
I have done several things to fix this:
I have, in my test file, put this:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' (with mysite being the correct dir I promise)
I have a settings file and a wsgi file, and my wsgi file does set the DJANGO_SETTINGS_MODULE:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
application = get_wsgi_application()
The only thing that has taken me out of this error was by setting up the configuration for that test class by going to Edit Configuations -> Environment -> Environment Variables and adding the DJANGO_SETTINGS_MODULE there. This only gets me a different error:
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
Plus, I have to do this for every test class and I can't run individual tests in the class, but must rather run the entire test suite in that class. Not a good solution...
I have manually (in the virtualenv) run export DJANGO_SETTINGS_MODULE=mysite.settings. This has not changed anything.
So, I am out of ideas and have followed all the advice I could find on SO. Is there something else I have to do in Pycharm? Again, the cmdline works fine, but I'd really rather not run tests this way - plus, I can't debug.
Edit: It may be worth noting that I am running the unit tests while my server is running (this should not make a difference), and I am also have the python interpreter pointed to the one in my virtualenv.
Try to open the Run/Debug Configuration window (you should find it in the top toolbar, clicking the dropdown menu near the play / debug button and Edit Configuration)
From here, you should see a list with the existing saved configurations where the last element should be Templates. Search Django tests under Templates. In the environment part, add DJANGO_SETTINGS_MODULE=mysite.settings to the environment variables. The next time you'll run a test that is not existing in your run/debug configurations, the template with the setting module set will be used.
If I were you, I will delete all the existing test configurations. Also, I suspect from your point 3, that you have probably a python test configured instead of a Django test (this is why you had the error django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet because Django was not loaded). If you have it, delete it too. Apply the configurations and retry to run the test.
When you run the test, ensure that a Django test is run, not a python one (you should see the Django logo near the test name in the run section and in the dropdown in the toolbar)

"Rake" or my customs tasks in Django

In Rails I can create a custom a job for rake which does whatever I want to and then run it as "rake my_task". What's a way to do it in Django?
In particular, I need to create such a job which read my own data files in a custom format, processes the data in a special way and them inserts it into the db. And I'm going to run it multiple times, not only once. To achieve that I created a pure python script and ran it but got an error
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
So a python script didn't work, there must be a django-way to do it.
The "Django Way" would be to create a custom command.
If you want to create an external python script, then there is also a way to do that explained in this stack overflow answer (EDIT: this is actually outdated for django 1.7) along with an example of how to create custom commands. I recommend the django documentation though if you're using the latest version of django.
On a related subject, check out fabric.
Edit:
For a django >= 1.7 standalone script:
import os
import django
from myapp import models
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
django.setup()
print models.MyModel.objects.get(pk=1)
There are 2 ways to do it on top of my head
1 - You can write a custom management command to be invoked by manage.py: https://docs.djangoproject.com/en/1.8/howto/custom-management-commands/
2 - The rake equivalence in python world is pyinvoke: https://github.com/pyinvoke/invoke, which is a successor of fabric that takes some design inspiration from rake itself.
When using invoke, if you need the django environment to be setup, use this https://docs.djangoproject.com/en/dev/ref/applications/#django.setup

Is there any reason why a project has no settings.py file?

I have inherited a Django 1.4 project from an uncooperative developer and am having to find my way around and try and set up a dev environment.
One of the issues I am having is a result of the fact there is no settings.py file in the project. In the directory where I would expect to find it, there are files like settings_production.py, settings_base.py etc. but none called settings.py. So when I try
python manage.py runserver
it complains about this. I have renamed one of them to simply settings.py and I get a little further. But I am obviously missing something - is there a valid reason for this situation to arise and if so, is there something I need to do in my local setup to allow this to work?
This is perfectly fine and used quite often. Different environments, like your local development environment and the actual production environment, often require different settings. You can pass the settings module to use to your manage.py command
or set the DJANGO_SETTINGS_MODULE in your command line environment.
manage.py runserver --settings=import.path.to.settings
# or
export DJANGO_SETTINGS_MODULE='import.path.to.settings'

What does INSTALLED_APPS setting in Django actually do?

What does this actually do? I recently branched out my project from 1 app into 6 different apps and forgot to update the INSTALLED_APPS part of my settings file. Everything still works even though I didn't list the new apps in. Is that supposed to happen? Do I need to include all my apps in INSTALLED_APPS?
yes.
INSTALLED_APPS helps django to sync the database, run tests, get the urls to work and more related issues.
Maybe your installed apps still works because the main one calls the others with imports, a django app is nothing more that a simple python module that is imported when called in the settings file, that's why you get a invalid syntax error after you run the development server because an import won't work with invalid syntax.

I change Python code, but can't see results

Sorry for totally stupid question, but the situation is that I have to make some changes to the Django website, and I have about zero knowleges in python.
I've been reading Django docs and found out where to make changes, but there is very strange situation. When I change view, template, config or anything on web site - nothing happens.
It looks like code is cached. When I completely delete the site's folder - everithing works fine except css stops working.
The only file that is vital and lays outside the site's folder is starter.py whith code
#!/usr/local/bin/pthon2.3
import sys, os
.... importing some pathes and other conf stuff
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
Please can anybody tell my what am I doing wrong?
Python web applications typically differ from PHP ones in that the software is not automatically reloaded once you change the source code. This makes sense because initialization, firing up the interpreter etc., doesn't have to be performed at each instance. It's not that the code is "cached"; it's only loaded once. (Python does cache its bytecode, but this it transparently detects changes, so you needn't worry about that.) So you need to find a means to restart the WSGI program. How this is done in your particular webhosting environment is for you to find out, with the help of the web host or system administrator.
In addition to this, Django does cache its views (if that feature is turned on). You'll need to invalidate the caches in that case.

Categories