首页 > 解决方案 > 通过用户模型 Django 访问配置文件信息

问题描述

您好,我是 django python 框架的初学者。我需要在我的博客应用程序中名为 user_posts.html 的文件上显示用户的图像和简历。我有它,我可以通过循环访问用户的帖子来访问用户的图像和简历。但是,我需要它,所以它只显示生物和图像一次。我在用户应用程序中有一个单独的 profile.html。在该文件中,我可以只执行 src="{{ user.profile.image.url }}" 和 {{ user.profile.bio }} 来访问用户信息,但这在我的 user_posts.html 中似乎不起作用因为我的项目结构。我不知道如何告诉 for 循环只检查一次以访问用户信息。

users_post.html

{% extends "blog/base.html" %}
{% block content %}
    
    <hr size="30">
    <div class="row">
        <div class="column left">
        {% for post in posts %}
                <img style= "float:left" src="{{ post.author.profile.image.url}}" width="125" height="125">
                <h5 style="text-align: left;">{{ post.author.profile.bio }}</h5>
        {% endfor %}
        </div>

视图.py

class UserPostListView(ListView):
    model = Post
    template_name = 'blog/user_posts.html' # <app>/<model>_<viewtype>.html
    context_object_name = 'posts'
    ordering = ['-date_posted']
    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')

模型.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')
    bio = models.TextField(default='enter bio text here')
    

    def __str__(self):
        return f'{self.user.username} Profile'

这就是问题的样子

任何帮助表示赞赏

标签: pythonhtmlcssdjango

解决方案


这是您可以使用的方法get_context_data()

class UserPostListView(ListView):
    model = Post
    template_name = 'blog/user_posts.html' # <app>/<model>_<viewtype>.html
    context_object_name = 'posts'
    ordering = ['-date_posted']
    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):
        """
        Add User Profile to the template context.
        """
        context = super().get_context_data(**kwargs)
        profile_user = get_object_or_404(User, username=self.kwargs.get('username'))
        context['profile_user'] = profile_user
        return context

然后{{ profile_user.profile.bio }},您将在模板中使用,而不是posts用于用户个人资料信息。

posts在用户还没有帖子(但有个人简介)的情况下,这可能比获取第一个对象并从该对象获取用户配置文件信息要好。

请注意,我们同时在 in和 in 中获取User对象,因此这不是超级有效的。有办法解决这个问题,但我会把它留给未来的编辑或你来优化:)get_querysetget_context_data

可能不推荐,但回答问题

由于您最初只是想获得第一个元素,这就是我的做法。


# Method 1
{% with first_post=posts|first %}
  {{ posts.user.profile.bio }}
  {{ posts.user.profile.image.url }}
{% endwith %}

# Method 2
{{ posts.0.profile.bio }}
{{ posts.0.profile.image.url }}

推荐阅读