【发布时间】:2020-02-15 08:00:24
【问题描述】:
没有获取媒体文件。与 User 模型相关的字段正在工作(例如 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 关系的 User 模型连接。
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
>与视图相关的代码。
class ProfileDetailView(DetailView):
model = User
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
【问题讨论】:
-
也显示你的模型
-
@arjun 模型已添加,请立即查看。与用户模型相关的字段正在工作(例如 object.username,object.email),但 ProfileImage 字段不工作。
-
@arjun 我现在已经添加了完整的 model.py。你需要 view.py 吗?
标签: django django-templates django-urls