我看不到图片在我的网站上显示为损坏。这是我尝试过的:
models.py
。Settings.py具有:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
图片:当前位于我的主项目目录中的“媒体”文件夹中。
static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
和导入的设置。{% load static %} and {{ post.image.url }}
。Ran服务器:
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'profiles/static/')
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
urls.py
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('post/<id>/', views.post, name='post'),
....
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
from django.db import models
from django.conf import settings
from PIL import Image
class Profile(models.Model):
title = models.CharField(max_length=200, blank=True, null=True)
bio = models.TextField(max_length=500, blank=True)
user = models.OneToOneField(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE, null=True)
def __str__(self):
return f'{self.user.username} Profile'
class Post(models.Model):
title = models.CharField(max_length=200)
post = models.TextField(max_length=100, blank=True)
image = models.ImageField(default='default.jpg',
upload_to='picsinposts')
profile = models.ForeignKey(Profile, on_delete=models.CASCADE,
blank=True, null=True)
def __str__(self):
return self.title
{% extends "base.html" %}
{% load static %}
{% block content %}
<html>
<body>
<div class= "Profile">
<h2> {{ profile.title }} </h2>
<p> {{ profile.bio }} </p>
{% if request.user == profile.user %}
<a href="{% url 'edit_profile' id=profile.id %}"> Edit your profile! </a>
{% endif %}
</div>
<br>
{% for post in post %}
<div class= "Posts">
<a href="{% url 'post' id=post.id %}"> {{ post.title }} </a>
<p> <img src="{{ post.image.url }}", style= "width:100px;"/> </p>
<a href="{% url 'follow' id=profile.id %}"> Follow Profile! </a>
Where my pictures live currently
我想念什么?
答案 0 :(得分:1)
您的静态URL必须位于项目的urls.py中。
删除此表单app/urls.py
,然后放入您的project's
urls.py中:
project / urls.py
urlpatterns = [
...... ..] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)