如何在 django 上添加个人资料图片



我一直在尝试向用户添加个人资料图片,但该文件似乎"未知",所以我认为错误出在个人资料上.html但我不知道如何解决它。

views.py

def profile(request, username=None):
if username:
post_owner = get_object_or_404(User, username=username)
user_posts = Profile.objects.filter(user_id=post_owner)
else:
post_owner = request.user
user_posts = Profile.objects.filter(user=request.user)
args1 = {
'post_owner': post_owner,
'user_posts': user_posts,
}
return render(request, 'profile.html', args1)

models.py

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_pic = models.ImageField(upload_to='profile_pics', null=True, blank="True", default="default.png")
def __str__(self):
return f'{self.user.username} Profile'

profile.hmtl

<h2 class="account-heading">{{ post_owner.username }}</h2>
<img class="account-img" src="{{ user.profile.profile_pics.url }}" style="max-width: 300px; max-height: 300px;margin-left: 15px;margin-right:15px;">
<h2 class="account-heading">{{ post_owner.first_name }}</h2>

顺便说一句,我已经安装了枕头,但我会添加 settings.py 和urls.y,以便您看到它:(

views.py

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

urls.py

from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', include('home.urls')),
path('admin/', admin.site.urls),
path('accounts/', include('accounts.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

您将字段定义为profile_pic但尝试在 html 文件中访问profile_pics。更改img元素的src属性,如下所示:

src="{{ user.profile.profile_pic.url }}"

最新更新