媒体文件未获取。与用户模型相关的字段正在运行(例如,object.username,object.email),但具有ProfileImage的字段不起作用。
添加了以下代码。
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)
配置如下。
STATIC_URL = '/static/'
STATICFILES_ROOT = os.path.join(BASE_DIR,'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
这些是html代码。
{%扩展'base.html'%}
{% block main %}
{{object.email}}
{{request.user}}
<img src="{{object.profileimage.image.url}}">
{% endblock %}
此模型与具有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)
与视图相关的代码。类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
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')
这对我有用。