簡體   English   中英

查看上傳到Django Admin的圖像

[英]Viewing images uploaded to Django Admin

我有一個簡單的Django管理頁面,可將圖像上傳到產品描述。 一切正常,直到我嘗試通過單擊產品信息中的路徑來查看圖像。 我收到此錯誤:

Page not found (404)
Request URL:    http://0.0.0.0:6666/the_image.jpg

我猜我需要在urls.py中聲明一些內容,但是我不知道從哪里開始。 我也嘗試在settings.py中更改我的媒體路徑,但是如果我更改為'/'以外的任何內容,我總是會收到錯誤消息

model.py

class Image(models.Model):
    product_image = models.ForeignKey(Product)
    image = models.ImageField(upload_to='/')

settings.py

MEDIA_ROOT = '/'
MEDIA_URL = '/'

admin.py

class InlineImage(admin.TabularInline):
    model = Image

class ProductAdmin(admin.ModelAdmin):
    inlines = [InlineImage]

文件在這里https://docs.djangoproject.com/en/dev/ref/settings/#media-root

您需要像這樣在設置文件中設置MEDIA_ROOT和MEDIA_URL

MEDIA_ROOT = /var/www/example.com/media/
MEDIA_URL = /media

並且您的upload_to應該應該是模型名稱或用於識別它的名稱。

image = models.ImageField(upload_to='image')

然后,鏈接應指向/media/image/NAME_OF_IMAGE.png

您還需要將urls.py設置為服務器媒體文件。 對於生產,您可能想在nginx中使用別名進行此操作。 參見https://docs.djangoproject.com/en/dev/howto/static-files/#serving-files-uploaded-by-a-user-during-development

其中說:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = patterns('',
    # ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM