-根urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('estate.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)- app urls.py
from django.urls import path
from . import views
from .views import index, about, category, PostListView, PostDetailView
urlpatterns = [
path('', views.index, name='index'),
path('about/', views.about, name='about'),
path('category/', views.category, name='category'),
path('liste/', PostListView.as_view(), name='liste'),
path('detail/<int:id>/', PostDetailView.as_view(), name='detail-list'),class lists(models.Model):
...
photos = models.ImageField(upload_to='photos/')
...
def __str__ (self):
return self.title from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView
from .models import *
def index(request):
listings = lists.objects.filter(is_active=True)
hit10 = lists.filter().order_by('-hit_counter')[:10]
context = {
'listings':listings,
'hit10':hit10,
}
return render(request, 'index.html', context)
class PostListView(ListView):
queryset = lists.objects.filter(is_active=True)
paginate_by = 5
class PostDetailView(DetailView):
def get_object(self):
id_=self.kwargs.get("id")
return get_object_or_404(listings, id=id_){% extends 'base.html'%}
{% load static %}
{% block content %}
<table class="table table-striped">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Photo</th>
<th scope="col">Title</th>
<th scope="col">Date</th>
</tr>
</thead>
{% for obj in object_list %}
{% if obj.is_active %}
<tbody>
<tr>
<th scope="row">{{ obj.id }}</th>
<td>{{ obj.photo.url }}</td>
<td><a href="{% url 'detail-list' obj.id %} ">{{ obj.title }}</a></td>
<td>{{ obj.date }}</td>
</tr>
{% endif %}
{% endfor %}
</tbody>
</table>
{% endblock content %}没有THUMBNAIL显示图像的结果是这样的: /media/photo/01.jpg
其他的都很好。谢谢。
发布于 2020-05-21 16:00:49
图像不会显示,因为您没有将url放在图像html标记中。已修改template.html文件:
...
<td> <img src=/static/{{ obj.photo.url }}></td>
...注意:‘static’应该是你在settings.py中设置的STATIC_URL。
发布于 2020-05-22 22:52:22
我找到了原因;
在template.py中
<tr>
<th scope="row">{{ obj.id }}</th>
THIS CODE SHOULD BE ---> <td>{{ obj.photo.url }}</td>
<td><a href="{% url 'detail-list' obj.id %} ">{{ obj.title }}</a></td>
<td>{{ obj.date }}</td>
</tr>
<tr>
<th scope="row">{{ obj.id }}</th>
LIKE THIS ONE ---> <td><img style="width:50%;" class="img-thumbnail" src="{{obj.photo.url}}" alt="IMG"></td>
<td><a href="{% url 'detail-list' obj.id %} ">{{ obj.title }}</a></td>
<td>{{ obj.date }}</td>
</tr>感谢所有提供帮助的人,特别是@Adil Shirinov。
https://stackoverflow.com/questions/61914460
复制相似问题