简体   繁体   English

Django 不会在 HTML 中显示数据库中的图像

[英]Django won't display image from database in HTML

Hi I am trying to get user profile images to display from a Django MySQL database corresponding to the user that is logged in..嗨,我正在尝试从与登录的用户相对应的 Django MySQL 数据库中获取要显示的用户个人资料图像。

Here is my settings.py这是我的settings.py

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
STATIC_DIR = os.path.join(BASE_DIR,'static')
MEDIA_DIR = os.path.join(BASE_DIR,'media')

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = [STATIC_DIR, ]

# Media files

MEDIA_ROOT = MEDIA_DIR
#MEDIA_DIRS = [MEDIA_DIR, ]
MEDIA_URL = '/media/'
ADMIN_MEDIA_PREFIX = '/admin/media/'

Here is my urls.py:这是我的 urls.py:

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^smartcity/',include('smartcity.urls')),
    #url(r'^accounts/register/$', MyRegistrationView.as_view(), name='registration_register'),
    #url(r'^accounts/register/$', views.register, name='registration'),
    url(r'^accounts/', include('registration.backends.simple.urls')),
    url(r'^admin/', admin.site.urls),
    url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}),
]

And this is what I have in the html file:这就是我在 html 文件中的内容:

src="{% static 'user.userprofile.picture.url' %}"

This is my table i am trying to retrieve the picture from: Database screenshot这是我试图从中检索图片的表格:数据库截图

I'm not sure how to get it to display, I thought my URL mapping was correct as i can view the image if i go to http://127.0.0.1:8000/media/profile_images/trump.jpg我不知道如何让它显示,我认为我的 URL 映射是正确的,因为如果我去http://127.0.0.1:8000/media/profile_images/trump.jpg我可以查看图像

Any ideas?有任何想法吗? Sorry I am a bit of noobie.对不起,我有点菜鸟。

FileField uploads to the media side of things, not static, so you just have to do; FileField上传到媒体端的东西,不是静态的,所以你只需要这样做;

<img src="{{ user.userprofile.picture.url }}" alt="" />

Here is an example of this scenario;这是这种情况的一个例子; https://www.simplifiedpython.net/django-file-upload-tutorial/ https://www.simplifiedpython.net/django-file-upload-tutorial/

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

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