python - 通过用户模型 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'
任何帮助表示赞赏
解决方案
这是您可以使用的方法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_queryset
get_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 }}
推荐阅读
- sql - 根据列值抓取值
- jquery - sortable - 获取放置项指针
- mql4 - Algotrading:如何合并这种类型的追踪止损?
- bash - Bash 剪切和排序问题
- ios - FCM-当用户单击通知时如何区分它是从 Firebase 控制台还是 HTTP 发送
- laravel - 模型在什么时候知道要使用哪个连接
- botframework - 如何为 Skype 机器人实现即时欢迎消息?
- excel - 如果 Excel 工作表公式中的语句为 True,如何添加可计算值
- php - 在 routes.php 文件中获取错误以将它们传递给另一个路由
- excel - 根据用户输入定义数字的小数位