简体   繁体   English

在网站中显示上传的图片 - Django

[英]Display uploaded images in the website - Django

I have been trying to display my images in my html page and I did do it correct but it wont work I don't know why this is the last update of django I have watched and read alot of videos and article and do the same as they told me to do but it not working the image wont work in my html template我一直在尝试在我的 html 页面中显示我的图像,我确实做对了,但它不起作用我不知道为什么这是 django 的最后一次更新他们告诉我这样做但它不起作用图像在我的 html 模板中不起作用

Hope anyone can help me with this Thank you希望有人能帮我解决这个问题谢谢

admin.py管理文件

from django.contrib import admin

# Register your models here.
from .models import *


admin.site.register(slideshowgo)

settings.py设置.py

STATIC_URL = '/static/'

MEDIA_URL = '/images/'

STATICFILES_DIRS = [
   BASE_DIR / 'static',
]

MEDIA_ROOT = BASE_DIR / 'static/images'

models.py模型.py

from django.db import models


class slideshowgo(models.Model):
image_one = models.ImageField(null=True,blank=True)

slideshow html幻灯片 html

<div class="slide">
<img class="mySlides imgslide" src="{{slideshowgo.image_one.url}}">
</div>

urls.py网址.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('card_store.url')),
] 

if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

In settings.py put the following config在 settings.py 中放置以下配置

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

And in your main urls.py file ( one which is located in the same app as of settings.py )并在您的主 urls.py 文件中(与 settings.py 位于同一应用程序中的文件)

Add this添加这个

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

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

This will work for DEBUG = True For DEBUG = False it won't as Django cannot server media files by itself, so you need to setup NGINX or APACHE.这将适用于 DEBUG = True 对于 DEBUG = False 它不会,因为 Django 不能自己服务媒体文件,因此您需要设置 NGINX 或 APACHE。

One workaround is to put the following URL's in your main urls.py ( Not recommended for production )一种解决方法是将以下 URL 放在您的主 urls.py 中(不推荐用于生产)

re_path(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
re_path(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM