Srikar Appalaraju
Srikar Appalaraju

Reputation: 73688

Test out small snippets of Django code

I am still in the development phase of a Django App. Before even writing my views.py, I test them out to see if my models are correctly defined. This I do it in the terminal by invoking

python manage.py shell

But oh so often I make some syntax error prompting me to abort the shell ctrl-D & retype everything. This process is taking forever. It would be better if I could write all this in some file just for my trials & if all's well copy it to views.py.

What's the process for this? Is it as simple as creating a trial.py in my app directory. Won't I have to import the Django env? What's the best way to do this?

Upvotes: 0

Views: 404

Answers (6)

newlife
newlife

Reputation: 778

I also had this problem before,

may be you could install ipython,which has a magic function called like this:

%save.

This will save what you input into a file .

and ipython is a very charming tool ,which can take the palce of standard python prompt perfectly.. It also have other wonderful things !

And in django , if you have install ipython, when you input python manage.py shell,

it will invoke ipython directly.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799290

You need to set the module used for settings.

Upvotes: 1

Tomasz Zieliński
Tomasz Zieliński

Reputation: 16367

For simpler cases you can use django-extensions add-on that contains shell_plus management command that is similar to the standard shell command but preloads all models.

Upvotes: 1

ffriend
ffriend

Reputation: 28552

Create your file-for-tests in the Django project directory and add path to your project to env variable:

import sys
sys.path.append(os.path.realpath(os.path.dirname(__file__)))

After that you'll be able to import any module from the project (e.g. models from models.py or just functions from views.py) and use your favorite IDE with it's editor and shell.

Upvotes: 1

Vinay Sajip
Vinay Sajip

Reputation: 99480

By all means create a trial.py for simple experimentation, then after doing

python manage.py shell

you can do

>>> import trial

and then invoke the code in trial, directly from the prompt, e.g.

trial.myfunc()

If you need to change things you can just save your changed trial.py and do

reload(trial)

Of course, you may need to recreate any existing objects in the interactive session in order to make use of your changes.

This should be seen as complementary to writing unit tests (as per Jani's answer), but I do find this approach useful for trying things out using iterative refinement.

Upvotes: 2

Jani Hartikainen
Jani Hartikainen

Reputation: 43253

How about writing unit tests? You can execute them easily with one command. You can probably get started by reading the django manual chapter on testing

Upvotes: 5

Related Questions