【发布时间】:2020-05-19 21:08:40
【问题描述】:
我正在使用 Django 构建博客,我对使用此工具非常陌生,我一直在尝试弄清楚如何在用户帖子视图中包含用户的个人资料图片。
基本上在用户帖子视图中,我做了一个过滤器---> www.site.com/user/"username",所以您可以按发布日期查看所有用户帖子。一切正常,但我没有得到用户个人资料图片。
我真的不知道这是 query_set 的问题还是我遗漏了什么。
views.py
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.models import User
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import Post
class UserPostListView(ListView):
model = Post
template_name = 'blog/user_posts.html'
context_object_name='posts'
paginate_by = 15
def get_queryset(self):
user = get_object_or_404(User, username=self.kwargs.get('username'))
return Post.objects.filter(author=user).order_by('-date_posted')
user_posts.html 我得到的是用户名,但不是用户个人资料。
<div class="col-auto"><img class="img-profile-st" src="{{ post.author.profile.image.url }}"></div>
<h1 class="mb-3" style="text-align: center;">Posted by {{ view.kwargs.username }} ({{ page_obj.paginator.count }})</h1>
models.py
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
【问题讨论】:
-
您添加了媒体网址吗? stackoverflow.com/q/5517950/67579
-
请注意,在生产中,您需要使用 nginx、apache 等来处理。