找不到Django媒体文件

问题描述 投票:0回答:1

媒体文件未获取。与用户模型相关的字段正在运行(例如,object.username,object.email),但具有ProfileImage的字段不起作用。

urls.py

添加了以下代码。

from django.conf.urls.static import static
from django.conf import settings

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

settings.py

配置如下。

STATIC_URL = '/static/'
STATICFILES_ROOT = os.path.join(BASE_DIR,'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')

profile_detail.html

这些是html代码。

{%扩展'base.html'%}

{% block main %}
{{object.email}}
{{request.user}}

<img src="{{object.profileimage.image.url}}">

{% endblock %}

model.py

此模型与具有OneToOne关系的用户模型连接。

def get_profile_upload_to(instance,filename):
    new_filename = '{}.{}'.format(uuid4,filename.split('.')[-1])
    return "profile/{}/{}".format(instance.user.id, new_filename)

class ProfileImage(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    image = models.ImageField(upload_to=get_profile_upload_to)
    uploaded = models.DateTimeField(auto_now_add=True)

views.py

与视图相关的代码。类ProfileDetailView(DetailView):型号=用户template_name ='user / profile_detail.html'

控制台错误代码

Not Found: /media/profile/1/function_uuid4_at_0x7fbf37ce42f0.jpeg
[18/Oct/2019 10:01:45] "GET /media/profile/1/function_uuid4_at_0x7fbf37ce42f0.jpeg HTTP/1.1" 404 3421
django django-templates django-urls
1个回答
0
投票

Urls.py

from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
  path('polls/', include('polls.urls')),
  path('admin/', admin.site.urls),
]

urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

post.html

  {% for post in posts %}
        <div class="col-md-4">
            <div class="card">
                <img class="card-img-top" src="{{post.image.url}}" alt="Card image">
                <div class="card-body">
                    <h4 class="card-title">{{post.title}}</h4>
                    <p class="card-text">{{post.content}}</p>
                </div>
            </div>
        </div>
   {% endfor %}

settings.py

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

这对我有用。

© www.soinside.com 2019 - 2024. All rights reserved.