【问题标题】:Django media files not loadingDjango媒体文件未加载
【发布时间】:2019-06-28 08:31:50
【问题描述】:

我有一个users 应用程序,profile 是在其models.py 中创建的模型。image 存在于/media/profile_pics/ 中,但即使在src 中提供完整路径后,它也不会加载。我不知道为什么。在下面添加相关文件。

models.py

from django.contrib.auth.models import User

from django.db import models
from django.contrib.auth.models import AbstractUser


class profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='media/default.jpg', upload_to='profile_pics')


def __str__(self):
    return f'{self.user.username} Profile'

profile.html

<!DOCTYPE html>

{% extends 'base2.html' %}
{% load crispy_forms_tags %}
{% load static %}


<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>profile</title>
</head>
{% block content %}
<body style="margin-left: 300px">
<div class="content-section">
    <div class="media">
        <img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
        <img class="rounded-circle account-img" src="E:\py-projects\hello-world\media\profile_pics\profile1.png">

    </div>
</div>

</body>
{% endblock %}

</html>

settings.py

STATIC_URL = '/static/'

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

STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),

]

urls.py(主urls.py,不是app的users)

from django.contrib import admin
from django.urls import path, include
from users.views import profile
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('users.urls'), name='index'),
    path('profile/', profile, name='profile'),

]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

【问题讨论】:

  • 您似乎没有设置任何东西来提供来自 MEDIA_URL 的文件。
  • 如何设置
  • 你肯定可以看到你已经为 STATIC_URL 做了一些事情,但没有为 MEDIA_URL 做一些事情。 (但请注意,两者都仅适用于 DEBUG。)
  • 我确实设置了MEDIA_URL = '/media/'
  • 叹息。看看你的网址。看看你为静态做了什么。然后对媒体做同样的事情。

标签: python django django-models django-media


【解决方案1】:

没有看到这个我觉得很愚蠢:|必须添加这个。

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

【讨论】:

    【解决方案2】:

    在你的 urls.py 中使用它

    from django.conf.urls import url
    from django.conf import settings
    from django.views.static import serve
    
    
    urlpatterns = [
        url(r'^media/(?P<path>.*)$', serve, {'document_root': 
            settings.MEDIA_ROOT}),
        url(r'^static/(?P<path>.*)$', serve, {'document_root': 
            settings.STATIC_ROOT}),
    ]
    

    在你的 settings.py 中

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-20
      • 2012-10-03
      • 1970-01-01
      • 2021-06-28
      • 2012-04-12
      • 2018-12-09
      • 1970-01-01
      相关资源
      最近更新 更多