Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a local file in django

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!

like image 587
fenomenoxp Avatar asked Oct 25 '12 10:10

fenomenoxp


People also ask

How do I view files in Django?

There is a file called urls.py on the myworld folder, open that file and add the include module in the import statement, and also add a path() function in the urlpatterns[] list, with arguments that will route users that comes in via 127.0. 0.1:8000/members/ . In the browser window, type 127.0.

How does Django read file data?

Django File Object The open() function opens the file in the given mode argument, and the write() method is used to write a file, and the read() method is used to read a file. At last, we have closed the file object and file using close() method. Here is the complete code to write and read a file.


1 Answers

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')) 
like image 114
Rag Sagar Avatar answered Sep 28 '22 10:09

Rag Sagar