'reading file in a django view function
EDITED in response to comments and answers:
I am new to django and web development and I feel like I'm missing something basic about how to use django views.
I have a django app that I set up following the instructions in the django tutorial: here. Specifically, I end up with the autogenerated directory and file structure described there:
mysite/
manage.py
settings.py
urls.py
myapp/
models.py
views.py
templates/
*.html
static/
*.css
In my app I receive some user input from a template form and save it in my model in a function in views.py.
Before doing this I want to run some functions to check the input - depending on what it is I decide whether or not and where to put it in the database and also what content to display to the user next.
For example, one thing I want to do is check whether the words that were input are in the dictionary. I have a word list in a text file and I want to check whether the words from the input are in that list.
I want to be able to do something like:
wordlist = set(w.strip() for w in open(filename).readlines())
Where should I put this text file and how can I refer to it (in order to open it) in views.py? Where should I put that line of code - is there a way to only make this set once and then access it whenever any user submits input?
Note that I tried just putting the text file in myapp/ and then doing open(filename) but I get an error:
IOError No such file or directory.
I also tried to put the file in static/ and then do open(STATIC_URL + filename) but I get an error:
NameError Name 'STATIC_URL' is not defined.
However I do have from django.contrib import staticfiles so it should be defined.
Solution 1:[1]
This is a very old post, but I was doing something similar and here is my solution of how to read text content in Django view.py
import os
def your_view_function(request):
module_dir = os.path.dirname(__file__) #get current directory
file_path = os.path.join(module_dir, 'data.txt') #full path to text.
data_file = open(file_path , 'rb') #I used'rb' here since I got an 'gbk' decode error
data = data_file.read()
# print("data=", data)
return whatever_you_need
Solution 2:[2]
Django is just Python. There are no special rules about accessing files in Django, you do it just as you would with any other Python script.
You don't give any examples or reason why open(filename) doesn't work. Assuming filename is an absolute path, and that the user that Django is running as has permission to open the file, it should definitely work. (Although note that relying on opening a file may not be the best design when it comes to a multi-user web site.)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Oscar Zhang |
| Solution 2 | Daniel Roseman |
