30

I'm quite stuck on this one! I am writing a Django view that reads data from an external database. To do this, I am using the standard MySQLdb library. Now, to load the data, I must do a very long and complex query. I can hard code that query in my view and that works just fine. But I think that is not practical; I want to be able to change the query in the future, so I try to load the statement from a text file. My problem is that I don't know where to store and how to open that file. Wherever I do, I get a "No such file or directory" error. Even saving it in the same directory than the code of the view fails.

Note that this is not an uploaded file; it's just an external file that completes my code. Any ideas? Thanks in advance!

fenomenoxp
  • 1,517
  • 3
  • 12
  • 13
  • Well, actually I had tried to put it in the same direcotry as the code of the view and normal open() function. As it had failed, I tried to find some information, but all I tried failed (IE: putting it in a "static" subdirectory of my app). An absolute path would work, but I still wanted more flexibility – fenomenoxp Oct 25 '12 at 11:22

2 Answers2

53

Keep the file in django project root and add the following in the settings.py file.

PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))

Then in the view do this.

import os
from django.conf.settings import PROJECT_ROOT

file_ = open(os.path.join(PROJECT_ROOT, 'filename'))

Update:

In newer Django versions BASE_DIR is already defined in the settings.py file. So you can do the following.

import os
from django.conf import settings

file_ = open(os.path.join(settings.BASE_DIR, 'filename'))
Rag Sagar
  • 2,314
  • 1
  • 18
  • 21
  • 6
    A small update that takes into account latest version of Django. `from django.conf import settings` `file_ = open(os.path.join(settings.BASE_DIR, 'filename'))` – mitenka Dec 13 '18 at 15:09
  • ... and what do you mean by 'newer or latest' version? `django 3.1`? – Gathide Nov 14 '20 at 05:48
5

For this use, I'd put it in the settings module. In settings.py, add e.g. MY_LONG_QUERY = 'from FOO select BAR...'. Then, in your view just load it from the settings like so:

from django.conf import settings
settings.MY_LONG_QUERY

But, this doesn't really answer your question. Assuming permissions and all are correct, keep a reference to your project root in your settings like this:

ROOT_PATH = os.path.split(os.path.abspath(__file__))[0]

And then again in your view, open your file like so:

from django.conf import settings

def read_from_database(request):
    f = open(os.path.join(settings.ROOT_PATH, 'myfile.db'))
    # Do something with f
jro
  • 9,300
  • 2
  • 32
  • 37
  • After the previous answer, that's just what I did hehe. But I also like the idea of saving the query in settings.py! – fenomenoxp Oct 25 '12 at 11:29