【发布时间】:2021-06-29 23:03:32
【问题描述】:
我的 models.py 中有这些模型 User Model
class User(AbstractBaseUser, PermissionsMixin):
"""Custom user model"""
email = models.EmailField(max_length=255, unique=True)
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
def __str__(self):
return '{}'.format(self.email)
UserInfo Model
class UserInfo(models.Model):
"""User's Info"""
user = models.OneToOneField(User, related_name="parent_user", on_delete=models.CASCADE)
image = models.ImageField(upload_to=user_image_file_path)
age = models.IntegerField()
bio = models.CharField(max_length=400)
def __str__(self):
return '{}'.format(self.user)
我的模板
在我的模板中,我传递了一些filtered User Profiles(假设按年龄过滤,如果age > 25)现在我还需要显示用户的姓名(first_name),但我不知道如何调用OneToOnefield反过来。非常感谢您的帮助:)。
{% for p in profiles %}
<div class="profile-container" style="position: relative">
<div class ="left-div">
<div class="mySlides fade">
<img src="media/{{p.image}}" style="width:100%" id="user-media-img">
<div class="text">
User First Name is : {{`What to type here?`}}
</div>
</div>
</div>
<div class="right-div">
<div class="details">
<h1>BIO</h1>
<p>{{p.bio}}</p>
<h1>Age:</h1>
<p>{{p.age}}</p>
</div>
</div>
</div>
{% endfor %}
编辑:
我的views.py:
我正在传递一个名为配置文件的列表,该列表已根据 2-3 种不同类型的过滤器过滤配置文件,因此代码将太多,无法在此处粘贴所有引用,
我在这里粘贴简短版本:
start =18
end=25
matching = UserInfo.objects.filter(
age__gte=start, age__lte=end
).values()
for z in matching:
if z['user_id'] not in rec_ids:
profiles.append(z)
print('profiles====', profiles)
context = {
'profiles' : profiles,
}
return render(request, 'home/news.html', context)
在此处粘贴输出
profiles==== [{'id': 18, 'user_id': 8, 'image': 'uploads/user/image/9d096190-73a0-4885-b4cd-ef6c7229b9eb.png', 'age': 23, 'bio': 'cool'}..etc]
谢谢:)
【问题讨论】:
-
{{ p.user.first_name }}
-
@khadimhusen 它不工作!
-
您能否包含您的视图以显示
profiles的定义? -
同意,请将视图添加到您的问题中。此外,在这种情况下实际上不需要它,因为这相对简单,但是您始终可以运行 shell
python manage.py shell,导入您的 User 或 UserInfo 模型(与视图相同),获取实例(例如u = User.objects.get(pk=1)),然后使用dir(u)查看该对象的所有属性。 -
@markwalker_,请检查编辑...也感谢您的建议
标签: python django model django-templates