settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
models.py:
class Product(models.Model):
name = models.CharField(max_length=30)
class Photo(models.Model):
product = models.ForeignKey(Product)
image = models.ImageField(upload_to="photo")
class Sale(models.Model):
product = models.ForeignKey(Product)
admin.py:
class PhotoInline(admin.StackedInline):
model = Photo
class ProductAdmin(admin.ModelAdmin):
inlines = [PhotoInline]
admin.site.register(Product, ProductAdmin)
admin.site.register(Sale)
从管理员添加照片后,我在媒体目录中存在照片并链接到照片:
http://127.0.0.1:8000/admin/sale/product/1/photo/1.jpg
但是当我转到这个链接时,我收到这样的消息:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/sale/product/1/photo/1.jpg/
Product object with primary key u'1/photo/1.jpg' does not exist.
当我尝试将图像输出到模板时:
src="{{ sale.product.photo_set.all.0.image.url }}"
我得到这样的照片链接:
http://127.0.0.1:8000/photo/1.jpg
有错误:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/photo/1.jpg
Using the URLconf defined in store.urls, Django tried these URL patterns, in this order:
^admin/
^$
The current URL, photo/1.jpg, didn't match any of these.
当我添加MEDIA_URL ='/ media /'时没有任何改变。我在管理员和网站上获得了一个链接:
http://127.0.0.1:8000/media/photo/1.jpg
得到第二个错误
答案 0 :(得分:3)