我的网站具有以下文件结构:
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)
此功能依次调用update_logo
中的profiles.models.py
:
def update_logo(self, value):
self.logo = value
self.save()
但是,当我上传照片时,my_image.png
会显示为user_1/my_image.png
,服务器会返回404,因为找不到该文件。我在这里做错了什么?
答案 0 :(得分:1)
Django定义了/profile/
,/update/
,/static/
和/
的网址。
未定义网址/user_1/
。
尝试将MEDIA_URL
更改为/media/
。