Django是否有类似于static
和url
的media
标签,并且如何设置它?
{% static 'styles/boo.css' %}
{% url 'some_app:some_name' %}
Is this possible: {% media 'what here' %}?
如何设置它?
Django是否有类似于static
和url
的media
标签,并且如何设置它?
{% static 'styles/boo.css' %}
{% url 'some_app:some_name' %}
Is this possible: {% media 'what here' %}?
如何设置它?
没有媒体模板标签。
在设置了 MEDIA_ROOT
和 MEDIA_URL
后,您可以通过引用其 url
属性来在模板中使用媒体文件。
例如:
class Foo(models.Model):
image = models.ImageField(
...
)
然后在你的模板中:
<img src="{{ foo_object.image.url }}">
此外,查看有关如何访问媒体文件的文档。
path('homes', include("page_home.urls"))
,它只能工作,但我想在主页URL path('', include("page_home.urls"))
中加载图片。 - Mr Coder{% load static %}
- Tobias Ernst{% load static %}
不是 Wagtail 特有的,它是 Django 的一部分:https://docs.djangoproject.com/en/dev/howto/static-files/ - Dan Swain{% get_media_prefix %}和{{MEDIA_URL}}通过上下文处理器都是你所需的良好替代品。
话虽如此,如果您真正想要实现的是呈现已上传的媒体文件(例如图像)的链接,则有更好的方法。
模型:
class Company(models.Model):
logo = models.ImageField()
@property
def logo_url(self):
if self.logo and hasattr(self.logo, 'url'):
return self.logo.url
模板:
<img src="{{company.logo_url}}"/>
@property 的原因是为了避免 ImageField 不包含图像的情况。在模板中直接访问 company.logo.url
会导致异常。
这实际上是 Django 中一个长期存在的问题:https://code.djangoproject.com/ticket/13327
对于媒体文件,我使用 django-imagekit
基本用法:
from django.db import models
from imagekit.models import ProcessedImageField
from imagekit.processors import ResizeToFill
models.py
class Photo(models.Model):
owner = models.ForeignKey(Project, on_delete=models.CASCADE)
photos = ProcessedImageField(upload_to='pagename/images',
processors=[ResizeToFill(900, 600)],
format='JPEG',
options={'quality': 90})
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'imagekit',
]
.html
{% load imagekit %}
{% thumbnail '100x50' source_file %}