I have a Django project called myproject, which has an app called myapp. I want to read a text file and load its contents into a list. I'm a little confused about static files and relative directories in Django, and my initial attempt is not working. So far, I have the following code...
In /myproject/settings.py:
STATIC_URL = '/static/'
In /myapp/static/myapp, there is a file called myfile.txt.
In /myapp/views.py:
with open('myapp/myfile.txt') as f:
lines = f.readlines()
When running the server, I get the error: No such file or directory: 'myapp/myfile.txt'
What am I doing wrong?
in your settings:
import os
gettext = lambda s: s
PROJECT_PATH = os.path.normpath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))
MEDIA_ROOT = os.path.join(PROJECT_PATH, "media")
MEDIA_URL = "/media/"
create a folder media under your app folder.
then put the file you want to read in that folder.
and try this in your views.py:
from django.conf import settings
with open(settings.MEDIA_ROOT + '\\yourfile.text', 'rb') as f:
lines = f.readlines()
Related
I have a small Django app, and I'm trying to access data from a CSV file (static/blog/dat.csv, the static folder is at the same level as the templates folder and views.py; and everything is inside my blog app) so I can use it to plot a graph on the browser using Chart.js. Aside from not being able to do that, the app is working fine.
I know I'm gonna need to pass some sort of context to the view function, but I don't know how I'd do that. Also, I have a couple of similar csv files, and using them as static files in my app seems simpler and easier than to add everything to a database to access them that way.
# views.py
from django.shortcuts import render
from django.contrib.staticfiles.storage import staticfiles_storage
import csv
def rtest(request):
url = staticfiles_storage.url('blog/dat.csv')
with open(url, 'r') as csv_file:
csv_reader = csv.reader(csv_file)
for line in csv_reader:
context += line
return render(request, 'blog/r.html', context)
# urls.py
urlpatterns = [
# ...
path('r-test/', views.rtest, name='blog-r-test'),
]
Here is the error I'm getting:
FileNotFoundError at /r-test/
[Errno 2] No such file or directory: '/static/blog/dat.csv'
I'm sure this is not the only error.
I know that the way I'm using the context variable is wrong, but that's just to kind of show what I'm trying to do. If I could just print one cell from the csv, I would view this as a win. Please help, thank you!
------Edit1-------
After using staticfiles_storage.path() instead of staticfiles_storage.url()
ImproperlyConfigured at /r-test/
You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path.
------Edit2------
I'm now able to find my csv file:
STATIC_URL = '/static/'
STATIC_ROOT = 'C:/Users/riccl/Documents/richie/Python/nuclear/main/book/static/book'
But my context variable still doesn't make any sense.
You need to use staticfiles_storage.path() to read the file. staticfiles_storage.url() will return the URL that a user will use to load the static file on your site
STATIC_ROOT is where all static files will be stored after you run collectstatic, most of the time this is set to <root of the project>/static/. This is also where staticfiles_storage.path() will look for static files.
You will also need to set STATICFILES_DIRS so that your file(s) can be found by collectstatic. I usually have a folder located at <root of the project>/<project name>/static/ which I add to STATICFILES_DIRS
I have a Django app that I just added to the already deployed Django web on Apache.
Because it is ran by Apache, path of the media folder seems to be different.
My app lets the user upload an excel file which then changes numbers and save as csv file.
(only showed relevant folders/code snippets)
Current directory
converts\
_init_.py
apps.py
forms.py
models.py
converter.py
urls.py
views.py
main\
settings.py
urls.py
wsgi.py
meida\
excels\
example.xlsx
csvs\
example.csv
static\
manage.py
settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
main\urls.py
urlpatterns = [
path('', RedirectView.as_view(url='/converts/')),
path('converts/', include('converts.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
The part that causes the problem is the following in converts/converter.py:
def convertExcel(name):
path = 'media/excels/'
key = path + name
wb = load_workbook(key)
Originally in development, a function in view calls convertExcel(example.xlsx) and the workbook, via media/excels/example.xlsx, finds the correct file to work with the loaded workbook. But in production server, it gives
FileNotFoundError: [Errno 2] No such file or directory: 'media/excels/example.xlsx'
My Question is:
Do I have to back track from where apache2.conf is to find the path? Or is there a way to set path to my django project so i can just set path in my convertExcel() as 'media/excels'? Or is there any other way I can call the uploaded workbook?
Any kind of help/comment would be appreciated.
Please comment if additional information is needed.
My guess is that you should use MEDIA_ROOT variable because it points to the uploaded files. So you would have
def convertExcel(name):
from django.conf import settings
path = os.path.join(settings.MEDIA_ROOT, 'excels')
key = os.path.join(path, name)
wb = load_workbook(key)
I am trying to implement Firebase cloud messaging push notifications in my Django project.
Firebase would look for a js file named firebase-messaging-sw.js in a project' root directory (no matter, what sort of project it is).
So, the problem is that I can't figure out what is my project's root directory (sorry, for being stupid), and how to make Firebase see this file. Just as an experiment, I copy-pasted the js file to each and every folder of my project, and still no success (Firebase service can't see the file).
Here's my settings.py file (with relevant content):
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ROOT_URLCONF = 'android_blend.urls'
WSGI_APPLICATION = 'android_blend.wsgi.application'
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
STATIC_URL = '/static/'
if DEBUG:
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR),"static","static-only")
#STATIC_ROOT = [os.path.join(BASE_DIR,"static-only")]
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),"static","media")
#MEDIA_ROOT = [os.path.join(BASE_DIR,"media")]
STATICFILES_DIRS = (
#os.path.join(os.path.dirname(BASE_DIR),"static","static"),
os.path.join(BASE_DIR,"static"),
)
My Django project layout is like this:
android_blend
android_blend
settings.py
url.py
wsgi.py
app1
app2
...
appN
manage.py
So the question is, what should I do in order for an outside service app (Google Firebase) be able to see the javascript file ?
In my browser, I get the following error:
A bad HTTP response code (404) was received when fetching the script.
I was also facing the same problem.
I tried it in the following way:
Add the following line in urls.py
url(r'^firebase-messaging-sw.js', views.firebase_messaging_sw_js),
Now add the function in view.py file
#csrf_exempt
def firebase_messaging_sw_js(request):
filename = '/static/firebase-messaging-sw.js'
jsfile = open(absAppPath + filename, 'rb')
response = HttpResponse(content=jsfile)
response['Content-Type'] = 'text/javascript'
response['Content-Disposition'] = 'attachment; filename="%s"' % (absAppPath + filename)
return response
So localhost:8000/firebase-messaging-sw.js will work properly...
Hope this will help you...
On pythonanywhere.com I have a django app. This is views.py:
def literature(request):
module_dir = os.path.dirname(__file__)
file_path = os.path.join(module_dir, 'literature.csv')
with open(file_path, 'r') as f:
...
File literature.csv is located at the same directory as views.py. But every time when I try to load the page I get FileNotFoundError. The same construction works normally on local server. Where is the bug?
This os.path.dirname(__file__) is giving you a relative path. On your local server, it just happens that it corresponds to the correct path. On PythonAnywhere, use the full path for module_dir. Like this: os.path.abspath(os.path.dirname(__file__))
in my models.py I have (myfile.txt is 3gb)
with open('/static/myfile.txt', 'rb') as f:
do something..
but it complains
No such file or directory: '/static/myfile.txt'
this is my settings.py
STATIC_ROOT = 'absolute_dir_to_project/app_name/static/'
STATIC_URL = '/static/'
Did I miss any step?
you should prepend the absolute path with SETTINGS's STATIC_URL so that it looks for myfile.txt inside Django:
from django.conf import settings # dont forget to import this guy
with open(settings.STATIC_URL + 'myfile.txt', 'rb') as f:
do something..
The open function is trying to open a file from disk with the path /static/myfile.txt, rather than requesting a file through your Django web app. It doesn't sound like you need to have this file in your static files folder, especially if it's huge and isn't intended for public consumption