1

I'm trying to create something like a photo gallery in Django. So far I'm working with the local Django copy and included web server and DB.

I'm done with most of the app logic but need to solve the static files problem. I need to have two locations - one for "media" which will be images and I expect to have them stored outside of the Django in future - now it's placed within Django root /files directory. So far I was able to make it working with the following:

settings.py

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'files'),)
STATIC_URL = "/photos/"

index.html

{% load static from staticfiles %}
<a href="{%static pic.path %}" class="gallery">Photo</a>

This works pretty well - when I click that link I can see picture stored at /files//picture.jpg being displayed as http://localhost:8000/photos/picture.jpg

But now I need to add some CSS and JS into that page and have no idea how to do that (besides placing them directly to /files directory which I need to avoid)

Thanks

2

2 Answers 2

2

You can fix this problem like this. Сhange this place of code

{% load static from staticfiles %}
<a href="{%static pic.path %}" class="gallery">Photo</a>

And write like this

{% load staticfiles %}

And you can add css in static dir and include css in template

<link rel="stylesheet" href="{% static 'css/style.css' %}">
2
  • static shouldn't be use for pics, media would be more appropriate.
    – Du D.
    Mar 24, 2016 at 15:03
  • Thanks all, finally I've made it working with the little adjustment to the previous answer. <link rel="stylesheet" href="{% static 'APP_NAME/css/style.css' %}"> Apr 9, 2016 at 20:27
0

To answer to your question follow the steps

Static

Create static files : We create the static files to link the html files with this 3 files : 1/ CSS files 2/ JS files 3/ IMAGES files ..

How to create the static files ?

1/ Go to the project files and create a folder name it static.

static / CSS-JS-Images

2/ Go To the settings file and search for static after the STATIC_URL.

add this Two line:

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

STATICFILESDIRS = [ os.path.join(BASE_DIR, 'here you type the direction of the static file') ]

Make sur that you're import the OS library

3/ finally you should collect static, to do that go on the terminal and add this code :

python manage.py collectstatic

here you find how to load static on the html file.

add this code on the top of the page :

{% load static %}

add this code To link CSS file with Html.

<link reel = 'stylesheet' href = " {% static 'dir of css file.css' %} "

May that help you.

1
  • please edit this so that everyone can read easily
    – arun n a
    Jul 4, 2021 at 16:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.