【问题标题】:Django won't display image from database in HTMLDjango 不会以 HTML 格式显示数据库中的图像
【发布时间】:2018-03-31 22:38:43
【问题描述】:

您好,我正在尝试从与已登录用户相对应的 Django MySQL 数据库中显示用户个人资料图像。

这是我的 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/'

这是我的 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}),
]

这就是我在 html 文件中的内容:

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

这是我试图从中检索图片的表格: Database screenshot

我不确定如何显示它,我认为我的 URL 映射是正确的,因为如果我转到 http://127.0.0.1:8000/media/profile_images/trump.jpg 可以查看图像

有什么想法吗?对不起,我有点菜鸟。

【问题讨论】:

    标签: python html mysql django


    【解决方案1】:

    FileField 上传到媒体方面的东西,不是静态的,所以你只需要这样做;

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

    这里是这个场景的一个例子; https://www.simplifiedpython.net/django-file-upload-tutorial/

    【讨论】:

    • 谢谢你成功了!我试图用这些 % 来做,但没有用..你的用双括号
    猜你喜欢
    • 1970-01-01
    • 2011-11-09
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-07
    相关资源
    最近更新 更多