gpt4 book ai didi

python - Django 找不到图像

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

我有一个具有以下文件结构的网站:

MyProject
+--- media
+--- user_1
+--- my_image
+--- profiles
+--- templates
+--- profiles
+--- create.html
+--- login.html
+--- profile.html
+--- urls.py
+--- models.py
+--- views.py
+--- MyProject
+--- settings.py

settings.py 中,我有我的 MEDIA_ROOT = os.path.join(BASE_DIR, 'media')MEDIA_URL = '/' 像这样设置,我将 'django.template.context_processors.media' 添加到 context_processors 中。在我的 urls.py 中,我有以下内容:

urlpatterns = [
url(r'^profile/(?P<profile_id>[0-9]+)/$', views.Details, name = "account"),
url(r'^update/', views.Update_Profile, name = "update"),
] + static(settings.STATIC_URL, document_root = settings.STATIC_ROOT) +\
static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

模板profile.html看起来像:

{% extends "base.html" %}
{% load profiles_extras %}

{% block content %}
{% load staticfiles %}
<div class="container-fluid">
<div class="row">
<div class="col-lg-8 col-lg-offset-2">

<!-- Store Information -->
<div class="col-lg-6">
<div class="panel panel-default">
<div class="panel-heading">
<h2>Store Information</h2>
</div>
<div class="center-block">

<!-- Change picture form -->
<form method="post" action="{% url 'update' %}" class="hidden form-inline" id="picture-change-form" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<input type="file" class="form-control" name="picture" accept="image/*">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>

{% if profile.logo %}
<img src="{{ profile.logo.url }}" class="img-responsive" id="logo" alt="Store Logo">
{% else %}
<img src="{% static 'no-image.png' %}" class="img-responsive" id="logo" alt="Store Logo">
{% endif %}
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}

上传个人资料图片时,会调用 profiles.views.py 中的此函数。

@login_required
def Update_Profile(request):
update_profile = Profile.objects.get(user = request.user)
has_updated = False
if ('picture' in request.FILES):
update_profile.update_logo( request.FILES['picture'] )
return redirect('profiles.views.Details', profile_id = update_profile.id)

该函数依次调用profiles.models.py中的update_logo:

def update_logo(self, value):
self.logo = value
self.save()

但是,当我上传照片时,my_image.png 它显示为 user_1/my_image.png 并且服务器返回 404,因为找不到该文件。我在这里做错了什么?

最佳答案

Django 已经为 /profile//update//static// 定义了 url。

网址 /user_1/ 未定义。

尝试将 MEDIA_URL 更改为 /media/

关于python - Django 找不到图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38817221/

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