我正在关注构建Web应用程序的Django书。当我构建一个模板时,除了我的图像之外,我得到的结果与书的结果相同 - 它们不存在。
我想知道是什么导致了这个问题。图像具有正确的URL,但是当我尝试打开它们时,Django声明" Page NOT 404 404"。
我正在粘贴下面的相关代码。另外,我包含了我的目录树的屏幕截图。
店/ models.py:
class Product(models.Model):
category = models.ForeignKey(Category,
related_name='products')
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
image = models.ImageField(upload_to='products/%Y/%m/%d',
blank=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.PositiveIntegerField()
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
模板:
<a href="{{ product.get_absolute_url }}">
<img src=" {% if product.image %}
{{ product.image.url }}
{%else %}
{% static 'img/no_image.png' %}
{% endif %}
">
</a>
views.py
def product_list(request, category_slug=None):
category = None
categories = Category.objects.all()
products = Product.objects.filter(available=True)
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
products = products.filter(category=category)
return render(request, 'shop/product/list.html',
{'category': category,
'categories': categories,
'products': products})
修改(settings.py和urls.py):
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^shop/', include('shop.urls', namespace='shop')),
url(r'^cart/', include('cart.urls', namespace='cart')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)