Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Models and Forms outside of Django?

Is it possible to run a view file using Django Model and Form outside of the Django environment?

like image 996
RadiantHex Avatar asked Apr 27 '10 14:04

RadiantHex


2 Answers

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.

like image 143
user85461 Avatar answered Oct 17 '22 22:10

user85461


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.

like image 20
joemar.ct Avatar answered Oct 17 '22 23:10

joemar.ct