【问题标题】:Add profile picture to UserPostListView in Django将个人资料图片添加到 Django 中的 UserPostListView
【发布时间】: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')

【问题讨论】:

标签: python django


【解决方案1】:

而不是使用这个

 src="{{ post.author.profile.image.url }}"

使用这个

 src="{% static post.author.profile.image.url %}"

由于所有静态文件都由静态 url 管理,这将对您有所帮助。 this is similar question.

【讨论】:

    【解决方案2】:

    我解决了这个问题,我在 def get_context_data 中为类写了另一个上下文。 所以 Views.py:

    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')
    
        def get_context_data(self, **kwargs):
            context = super(UserPostListView, self).get_context_data(**kwargs)
            user = get_object_or_404(User, username=self.kwargs.get('username'))
            context['postuser'] = Post.objects.filter(author=user).order_by('-date_posted')[:1]
            context['posts'] = Post.objects.filter(author=user).order_by('-date_posted')
            return context
    

    【讨论】:

      猜你喜欢
      • 2020-09-18
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-29
      • 1970-01-01
      相关资源
      最近更新 更多