gpt4 book ai didi

python - 如何在 Django 中使用来自数据库的路径在网页上呈现图像?

转载 作者:太空宇宙 更新时间:2023-11-04 03:17:57 25 4
gpt4 key购买 nike

enter image description here所以我试图在网页上显示图像,我将数据库中的图像路径保存为 media/imagename 并在我的 html 页面中我这样做:

{% for stuff in profile %}
<div class="alert alert-success" role="alert"> {{ stuff.text }} </div>

<img scr='/Users/Username/PycharmProjects/social-django-1.9/mysite/media/media/{{ stuff.thumbnail }}' width="200">

{% endfor %}

在我的 settings.py 中我这样做:

MEDIA_ROOT = os.path.join(PROJECT_ROOT, '/Users/Username/PycharmProjects/social-django-1.9/mysite/media/media')

但是图像不显示。我在这里做错了什么?谢谢!

编辑:

#urls.py
from django.conf.urls import patterns, url
from django.conf import settings

from social import views


urlpatterns = [


# main page
url(r'^$', views.index, name='index'),
# signup page
url(r'^signup/$', views.signup, name='signup'),
# register new user
url(r'^register/$', views.register, name='register'),
# login page
url(r'^login/$', views.login, name='login'),
# user doesnt exist webpage
url(r'^user-doesnt-exist/$', views.login, name='user-doesnt-exist'),
#page to show that the password is incorrect
url(r'^wrongpass/$', views.login, name='wrongpass'),
#webpage to show an error when a user tries to input nothing in the fields when signing up
url(r'^novalues/$', views.register, name='novalues'),
# logout page
url(r'^logout/$', views.logout, name='logout'),
# members page
url(r'^members/$', views.members, name='members'),
#invites page
url(r'^invites/$', views.invites, name='invites'),
# friends page
url(r'^friends/$', views.friends, name='friends'),
# user profile edit page
url(r'^profile/$', views.profile, name='profile'),
# messages page
url(r'^messages/$', views.messages, name='messages'),
# Ajax: check if user exists
url(r'^checkuser/$', views.checkuser, name='checkuser'),
#commiting again


]


if settings.DEBUG:
urlpatterns += patterns(''(r'^media/(P<path>.*)$','django.views.static.serve',
{'document_root':settings.MEDIA_ROOT,'show_indexes':True})),

最佳答案

尝试将您的 MEDIA_ROOT 设置为:

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

MEDIA_URL = '/media/'

并在你的项目urls.py文件中添加:

from django.conf import settings
from django.conf.urls import patterns

if settings.DEBUG:
urlpatterns += patterns('', (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}))

然后,在您的模板中像这样调用图像:

{% if stuff.thumbnail %}
<img src="{{ object.thumbnail.url }}">
{% endif %}

models.py 中:

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

Here的一些关于服务媒体文件的重要文档,包括如何在开发过程中服务它们。

关于python - 如何在 Django 中使用来自数据库的路径在网页上呈现图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35634193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com