Django 템플릿에 이미지 파일을 어떻게 포함하나요?
저는 Django를 처음 접했고 제가 개발중인 'dubliners'라는 간단한 프로젝트와 'book'이라는 앱을 통해 배우려고합니다. 디렉토리 구조는 다음과 같습니다.
dubliners/book/ [includes models.py, views.py, etc.]
dubliners/templates/book/
각 웹 페이지의 헤더에 표시해야하는 JPG 파일이 있습니다. 파일을 어디에 저장해야합니까? 템플릿을 사용하여 태그를 표시하려면 어떤 경로를 사용해야합니까? 다양한 위치와 경로를 시도했지만 지금까지 아무것도 작동하지 않습니다.
...
아래 게시 된 답변에 감사드립니다. 그러나 이미지에 대한 상대 경로와 절대 경로를 모두 시도했지만 여전히 웹 페이지에 깨진 이미지 아이콘이 표시됩니다. 예를 들어, 홈 디렉토리에 이미지가 있고 템플릿에서이 태그를 사용하는 경우 :
<img src="/home/tony/london.jpg" />
이미지가 표시되지 않습니다. 그러나 웹 페이지를 정적 HTML 파일로 저장하면 이미지가 표시되므로 경로가 정확합니다. Django와 함께 제공되는 기본 웹 서버는 특정 경로에있는 경우에만 이미지를 표시할까요?
프로덕션에서는 호스트에 미디어 파일이 저장되어있는 위치를 가리키는 템플릿에서 생성 된 HTML 만있을 것입니다. 따라서 템플릿은 예를 들어
<img src="../media/foo.png">
그런 다음 관련 파일이있는 디렉토리가 있는지 확인합니다.
개발 중은 다른 문제입니다. django 문서는 여기에 링크하고 입력하는 것이 더 효과적 일만큼 간결하고 명확하게 설명하지만 기본적으로 디스크 위치에 대한 하드 코딩 된 경로로 사이트 미디어에 대한보기를 정의합니다.
바로 여기 .
이 시도,
settings.py
# typically, os.path.join(os.path.dirname(__file__), 'media')
MEDIA_ROOT = '<your_path>/media'
MEDIA_URL = '/media/'
urls.py
urlpatterns = patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)
.html
<img src="{{ MEDIA_URL }}<sub-dir-under-media-if-any>/<image-name.ext>" />
경고
조심하세요! 를 사용 Context()
하면에 대한 빈 값이 생성됩니다 {{MEDIA_URL}}
. 대신를 사용해야합니다 RequestContext()
.
도움이 되길 바랍니다.
귀하의 질문은 MEDIA_ROOT에 저장된 파일에 관한 것이지만 때로는 해당 유형의 콘텐츠를 더 이상 만들 계획이 없을 때 콘텐츠를 정적으로 저장할 수 있습니다.
드문 경우 일 수 있지만 어쨌든 사이트에 "오늘의 사진"이 너무 많고 이러한 파일이 모두 하드 드라이브에있는 경우?
이 경우 STATIC에 이러한 콘텐츠를 저장하는 것에 대한 반대가 없습니다.
그리고 모든 것이 정말 간단 해집니다.
공전
STATIC_ROOT에 저장된 정적 파일에 연결하기 위해 Django는 정적 템플릿 태그와 함께 제공됩니다. RequestContext를 사용하는지 여부에 관계없이 이것을 사용할 수 있습니다.
{% load static %} <img src="{% static "images/hi.jpg" %}" alt="Hi!" />
공식 django 1.4 문서 에서 복사 / 내장 템플릿 태그 및 필터
이 작업을 이틀 동안 견고하게 보냈기 때문에 솔루션도 공유 할 것이라고 생각했습니다. 2010 년 11 월 26 일 현재 분기는 1.2.X이므로 settings.py에 다음이 있어야합니다 .
MEDIA_ROOT = "<path_to_files>" (i.e. /home/project/django/app/templates/static)
MEDIA_URL = "http://localhost:8000/static/"
* (MEDIA_ROOT는 파일이있는 곳이고 MEDIA_URL은 템플릿에서 사용하는 상수입니다.) *
그런 다음 url.py 에 다음을 배치하십시오.
import settings
# stuff
(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),
그런 다음 HTML에서 다음을 사용할 수 있습니다.
<img src="{{ MEDIA_URL }}foo.jpg">
장고가 작동하는 방식 (내가 생각할 수있는 한 :
- html 파일에서 MEDIA_URL을 setting.py에있는 MEDIA_URL 경로로 대체합니다.
- url.py에서 MEDIA_URL과 일치하는 항목을 찾은 다음 일치하는 항목을 찾으면 (예 : r '^ static / (? P. ) $'*가 http : // localhost : 8000 / static / 과 관련됨 ) 검색합니다. MEDIA_ROOT의 파일에 대해로드 한 다음
프로젝트 루트 아래의 / media 디렉토리
Settings.py
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
urls.py
urlpatterns += patterns('django.views.static',(r'^media/(?P<path>.*)','serve',{'document_root':settings.MEDIA_ROOT}), )
주형
<img src="{{MEDIA_URL}}/image.png" >
개발
중 앱 폴더에서 'static'이라는 폴더 이름을 만들고 해당 폴더에 사진을 저장합니다.
사진 사용을 사용하려면 :
<html>
<head>
{% load staticfiles %} <!-- Prepare django to load static files -->
</head>
<body>
<img src={% static "image.jpg" %}>
</body>
</html>
프로덕션 :
모든 것이 개발과 동일합니다. Django에 대한 매개 변수를 몇 개 더 추가하면됩니다.
settings.py에 추가
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
(모든 앱의 정적 파일이 저장 될 폴더를 준비합니다)당신의 앱이 있는지 확인하십시오
INSTALLED_APPS = ['myapp',]
in terminall run command python manage.py collectstatic (this will make copy of static files from all apps included in INSTALLED_APPS to global static folder - STATIC_ROOT folder )
Thats all what Django need, after this you need to make some web server side setup to make premissions for use static folder. E.g. in apache2 in configuration file httpd.conf (for windows) or sites-enabled/000-default.conf. (under site virtual host part for linux) add:Alias \static "path_to_your_project\static"
Require all granted
And that's all
If your file is a model field within a model, you can also use ".url" in your template tag to get the image.
For example.
If this is your model:
class Foo(models.Model):
foo = models.TextField()
bar = models.FileField(upload_to="foo-pictures", blank = True)
Pass the model in context in your views.
return render (request, "whatever.html", {'foo':Foo.objects.get(pk = 1)})
In your template you could have:
<img src = "{{foo.bar.url}}">
Your
<img src="/home/tony/london.jpg" />
will work for a HTML file read from disk, as it will assume the URL is file:///home/...
. For a file served from a webserver though, the URL will become something like: http://www.yourdomain.com/home/tony/london.jpg
, which can be an invalid URL and not what you really mean.
For about how to serve and where to place your static files, check out this document. Basicly, if you're using django's development server, you want to show him the place where your media files live, then make your urls.py
serve those files (for example, by using some /static/
url prefix).
Will require you to put something like this in your urls.py
:
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '/path/to/media'}),
In production environment you want to skip this and make your http server (apache, lighttpd, etc) serve static files.
Another way to do it:
MEDIA_ROOT = '/home/USER/Projects/REPO/src/PROJECT/APP/static/media/'
MEDIA_URL = '/static/media/'
This would require you to move your media folder to a sub directory of a static folder.
Then in your template you can use:
<img class="scale-with-grid" src="{{object.photo.url}}"/>
I tried various method it didn't work.But this worked.Hope it will work for you as well. The file/directory must be at this locations:
projec/your_app/templates project/your_app/static
settings.py
import os
PROJECT_DIR = os.path.realpath(os.path.dirname(_____file_____))
STATIC_ROOT = '/your_path/static/'
example:
STATIC_ROOT = '/home/project_name/your_app/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS =(
PROJECT_DIR+'/static',
##//don.t forget comma
)
TEMPLATE_DIRS = (
PROJECT_DIR+'/templates/',
)
proj/app/templates/filename.html
inside body
{% load staticfiles %}
//for image
img src="{% static "fb.png" %}" alt="image here"
//note that fb.png is at /home/project/app/static/fb.png
If fb.png was inside /home/project/app/static/image/fb.png then
img src="{% static "images/fb.png" %}" alt="image here"
If you give the address of online image in your django project it will work. that is working for me. You should take a shot.
참고URL : https://stackoverflow.com/questions/901551/how-do-i-include-image-files-in-django-templates
'IT박스' 카테고리의 다른 글
녹아웃보기 모델에 대한 변경 감지 (0) | 2020.11.23 |
---|---|
preg_replace를 사용하여 영숫자가 아닌 모든 문자 제거 (0) | 2020.11.23 |
테이블 구조를 새 테이블로 복사 (0) | 2020.11.23 |
Rails, Ruby, 배열 정렬 방법? (0) | 2020.11.23 |
Google 차트 (JS)-차트에 투명한 배경을 사용하는 방법이 있습니까? (0) | 2020.11.23 |