我想用 Django 創建預覽 auhors 個人資料和帖子的 pege。
我創建了 UserPostListView 類,然后我想按作者姓名搜索 Profile 模型并獲取組態檔。
我怎樣才能做到這一點?
所有代碼在這里
模型.py
class Profile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg',upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
def save(self):
super().save()
img = Image.open(self.image.path)
output_size = (300,300)
img.thumbnail(output_size)
img.save(self.image.path)
views.py(UserPostListView 類)
class UserPostListView(ListView):
model = Post
template_name = 'blog/user_posts.html'
context_object_name = 'posts'
paginate_by = 5
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')
def get_context_data(self, **kwargs):
context = super(UserPostListView, self).get_context_data(**kwargs)
context['profiles'] = Profile.objects.all()
return context
uj5u.com熱心網友回復:
如果我理解,您希望您的帖子查詢集中的帖子的作者個人資料是單個用戶,因此您可以在您的帖子get_context_data中獲取每個帖子的作者。
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["profile"] = Profile.objects.filter(user__username=self.kwargs.get("username"))
return context
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/467683.html
下一篇:listview沒有正確獲取資料
