gpt4 book ai didi

python - django 1.8 中的 ImageField 类不在模板中显示图像

转载 作者:太空宇宙 更新时间:2023-11-04 07:37:46 26 4
gpt4 key购买 nike

根据代码,图像应该显示在 index.html 模板上,但是 img src 似乎有一些问题

我的models.py

from django.db import models


class Rockinfo(models.Model):
rock_name = models.CharField(max_length=200,default="ac/dc")
rock_img = models.ImageField(upload_to="%Y/%m/%d",default="1992/08/92")
rank = models.IntegerField(default=0)

def __str__(self):
return self.rock_name

我的admin.py

from django.contrib import admin
from .models import Rockinfo, Rockvids

class ChoiceInline(admin.TabularInline):
model = Rockvids
extra = 10

class RockinfoAdmin(admin.ModelAdmin):
fieldsets = [
('The Fucking Band', {'fields': ['rock_name']}),
('Image', {'fields': ['rock_img']}),
]
inlines = [ChoiceInline]
list_display = ('rock_name', 'rock_img')
list_filter = ['rank']
search_fields = ['rock_name']


admin.site.register(Rockinfo, RockinfoAdmin)

我的应用程序的 urls.py

 from django.conf.urls import url

from . import views

urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
]

我项目的models.py

 from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
url(r'^rockinglist/', include('rockinglist.urls', namespace="rockinglist")),
url(r'^admin/', include(admin.site.urls)),
]

我的views.py 文件

   from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.views import generic
from .models import Rockvids, Rockinfo


class IndexView(generic.ListView):
template_name = 'rockinglist/index.html'
context_object_name = 'latest_rockinfo_list'

def get_queryset(self):
return Rockinfo.objects.order_by('-rank')[:5]

index.html 文件

   {% if latest_rockinfo_list %}
<ul>
{% for rockinfo in latest_rockinfo_list %}
<h1>{{ rockinfo.rock_name }}</a></li>
<img src="img\{{ rockinfo.rock_img }}" alt="ac/dc">
{% endfor %}
</ul>
{% else %}
<p>No</p>
{% endif %}

我认为问题出在图像的根目录上。不知何故 django 无法访问图像。我想显示 rock_name 以及相关的 rock_img。谁能帮我解决这个问题。在此先致谢。

最佳答案

在您项目的 urls.py 中,添加以下内容:

# your other imports here ...
# ...
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
# ... the rest of your URLs ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

在你的 settings.py 文件中,确保你有这个:

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, "media")

在你的模板中:

<img src="{{ rockinfo.rock_img.url }}" alt="ac/dc">

注意:如果 BASE_DIR 未在您的设置中定义,请将其放在您的设置文件之上:

import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

关于python - django 1.8 中的 ImageField 类不在模板中显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30666609/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com