我希望你能帮我解决我的Django项目。我可以在media_cdn文件夹下,根据slug的名称在文件夹中上传图像。当我尝试在帖子列表中显示图像并发布时,会出现问题。
请您查看我的代码并提供解决方案。我花了好几个小时试图让它发挥作用。请帮忙。
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media_cdn/')
models.py
def upload_location(instance, filename):
return "%s/%s" %(instance.slug, filename)
class Post(models.Model):
category = models.ForeignKey(Category)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique=True)
image = models.ImageField(upload_to=upload_location,
null=True,
blank=True,
width_field="width_field",
height_field="height_field")
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
body = models.TextField()
date = models.DateTimeField()
updated = models.DateTimeField(auto_now=True)
postlist.html
{% block content %}
{% for post in posts %}
<div class="container w3-card-4">
{% if post.image %}
<img src="{{ post.instance.image.url }}">
{% endif %}
...
post.html
{% block content %}
<div class="row">
<div class="container w3-card-4">
{% if instance.image %}
<img src= "{{ instance.image.url }}" class="img-responsive">
{% endif %}
...
url.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('personal.urls')),
url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
我不知道还有什么可以尝试从文件夹中调用该图像。任何建议将不胜感激。谢谢!
答案 0 :(得分:1)
使用post.image.url
代替post.instance.image.url
。查看documentation。
ImageField
会继承包含FileField
的{{1}}的所有属性。