【发布时间】: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