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!
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.
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.
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'))
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