简体   繁体   中英

How To add images in Django project

I have problem with adding images in Django project, my project is

my_app
  manage.py
  my_app 
    urls.py 
    views.py 
    settings.py 
    templates
     home.html
    static
     img
       image1.png

in settings.py

is all set by default

STATIC_URL = '/static/'

In home.html I aded code

{% load staticfiles %}

<img src="{% static 'img/image1.png' %}" />

but it can't load images , page not found

127.0.0.1:1000/static/img/openicon2.png

Page not found (404)
Request Method:     GET
Request URL:    127.0.0.1:1000/static/img/openicon2.png

Can someone help me ? maybe i need to modify urls.py ?

In my experience I've done the following in my settings.py and everythings works ok

import os.path,sys
CURRENT_DIR = os.path.dirname(__file__).replace('\\','/')
PROJECT_ROOT = os.path.abspath(os.path.join(CURRENT_DIR, os.pardir))

# other codes and stuff

I've added a variable named deveop and I change it depends on if my application runs on development server or apache

DEVELOP = True

# other codes and stuff

if DEVELOP == False:
    MEDIA_ROOT = os.path.join(PROJECT_ROOT,'media')

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = '/media/'

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
if DEVELOP == False:
    STATIC_ROOT = os.path.join(PROJECT_ROOT,'static')

# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    os.path.join(PROJECT_ROOT,'static'),
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

Simply add,

In settings.py:

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

In project's urls.py :

from django.conf.urls.static import static
from my_app import settings

urlpatterns = [.....]+static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT)

Then you can add image dynamically!!

In Templets:

<img ... src="{{key.image.url}}" ... >

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM