javad75
javad75

Reputation: 1435

Django template: static files in app directory

In Django settings.py file we have

STATIC_URL = '/static/'

And in each app directory I have static folder for css, js files.

For example:

├── myapp
│   ├── migrations
│   ├── __pycache__
│   ├── static
│   └── templates

When I use {% static "......." %} in *.html file

For example

  <link rel="stylesheet" href="{% static "style/fesahat.css" %}" />
  <link rel="stylesheet" href="{% static "style/loginStyle.css" %}" />

In output render django creates URL like this:

mysite.com/static/style/fesahat.css
mysite.com/static/style/loginStyle.css

I want to create the URL like this:

mysite.com/myapp/templates/static/style/fesahat.css
mysite.com/myapp/templates/static/style/loginStyle.css

Upvotes: 3

Views: 1670

Answers (3)

Majid Aveiro
Majid Aveiro

Reputation: 1

The way you use declare the static file is not right, in your example:

  <link rel="stylesheet" href="{% static "style/fesahat.css" %}" />

You are closing the double quotes when declaring the path to your css files, You should combine double and single quotes like this:

  <link rel="stylesheet" href="{% static 'style/fesahat.css' %}" />

Upvotes: 0

Muhammad Faizan Fareed
Muhammad Faizan Fareed

Reputation: 3758

@Daniel Roseman is right. Always use meaning full names.

STATIC_URL = '/static/' #This is URL prefix so use any prefix

Always use name-spacing in each app level static directory.

app1

app1/static/app1/files

app2

app2/static/app2/files 

static file namespacing

Now we might be able to get away with putting our static files directly in my_app/static/ (rather than creating another my_app subdirectory), but it would actually be a bad idea. Django will use the first static file it finds whose name matches, and if you had a static file with the same name in a different application, Django would be unable to distinguish between them. We need to be able to point Django at the right one, and the best way to ensure this is by namespacing them. That is, by putting those static files inside another directory named for the application itself.

You can namespace static assets in STATICFILES_DIRS by specifying prefixes.

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 600051

No you don't. Static files are not templates; don't put them there.

Upvotes: 2

Related Questions