4

I know there have been many questions here on accessing static files in a Django project, but I could not find a satisfactory answer to a problem I am dealing with. So, here's my project structure:

.
├── project
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   ├── wsgi.py
├── db.sqlite3
├── manage.py
└── app
    ├── admin.py
    ├── __init__.py
    ├── migrations
    │   ├── __init__.py
    ├── models.py
    ├── static
    │   └── app
    │       └── file.txt
    ├── tests.py
    ├── urls.py
    └── views.py

As per Django 1.7 documentation I have stored the static file file.txt in app/static/app folder. Now, how do I reference this file in a view? Lets just say I need to read the contents of this file for every call defined in app/views.py.

As usual, I have default setting of STATIC_URL = '/static/' in project/settings.py

Thanks

abhinavkulkarni
  • 2,284
  • 4
  • 36
  • 54

2 Answers2

8

You can import the static template tag into your view and use it as such:

from django.templatetags.static import static

url = static('app/file.jpg')
Joseph
  • 12,678
  • 19
  • 76
  • 115
5

You can do this by defining STATIC_ROOT in your settings. Then before running your project you can run

python manage.py collectstatic

And the static files then can be accessed using:-

file = open(os.path.join(settings.STATIC_ROOT, 'app/a.txt'))

This is basically the way, it is supposed to be done in a production environment, as static files are hosted separately from the django html views.

To load the name of app dynamically in project/urls.py

url(r'^', include('app.urls', app_name="app")),

and then in views:-

from django.core.urlresolvers import resolve
def appname(request):
    return resolve(request.path).app_name
Siddharth Gupta
  • 1,573
  • 9
  • 24