Is it possible to run a view file using Django Model and Form outside of the Django environment?
It is possible. Django is fairly good at being straight python without much magic, so you can usually decouple things. Views are just functions, and can be called from any other python code.
To use the ORM, you'll have to set up the django environment in your script. Looking at a "manage.py" file shows how to do this:
from django.core.management import setup_environ
import settings
setup_environ(settings)
Now, you can call whatever view you want:
from myapp.views import some_view
some_view(...)
Keep in mind that the convention is for view functions to take an HttpRequest object as their first parameter, and to return a HttpResponse object. You could build a request object yourself:
from django.http import HttpRequest
result = some_view(HttpRequest(), ...)
But if you really aren't interested in using HttpResponse or HttpRequest objects, perhaps you should just not call your methods "views". Maybe they're "utils" or something else. None of this is enforced by Django, but it's good form to follow a convention like that so other programmers can read your code.
Edit: 2010-05-24: Fixed "setup_environ" (erroneously had "execute_manager" previously). Reference.
In Django 1.6, this can be simply done by putting the project directory in the path, then set the DJANGO_SETTINGS_MODULE environment variable as shown below:
import sys
import os
sys.path.append(path_to_the_project_dir)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectname.settings')
Then, you can start importing your models.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With