我正在尝试制作一个用户面板,其中用户配置文件信息(如化身、加入日期等)将和他们的主题一起展示。以下是这样的观点:
def topic(request, topic_id):
"""Listing of posts in a thread."""
posts = Post.objects.select_related('creator') \
.filter(topic=topic_id).order_by("created")
posts = mk_paginator(request, posts, DJANGO_SIMPLE_FORUM_REPLIES_PER_PAGE)
topic = Topic.objects.get(pk=topic_id)
topic.visits += 1
topic.save()
return render_to_response("myforum/topic.html", add_csrf(request, posts=posts, pk=topic_id,
topic=topic), context_instance=RequestContext(request))
主题模式是:
class Topic(models.Model):
title = models.CharField(max_length=100)
description = models.TextField(max_length=10000, null=True)
forum = models.ForeignKey(Forum)
created = models.DateTimeField()
creator = models.ForeignKey(User, blank=True, null=True)
visits = models.IntegerField(default = 0)
UserProfile模型:
class UserProfile(models.Model):
username = models.OneToOneField(User)
name = models.CharField(max_length=30, blank=True)
city = models.CharField(max_length=30, blank=True)
country = models.CharField(
max_length=20, choices= COUTNRY_CHOICES, blank=True)
avatar = ImageWithThumbsField(), upload_to='images', sizes=((32,32),(150,150),(200,200)), blank=True)
created_at = models.DateTimeField(auto_now_add=True, blank=True)
updated_at = models.DateTimeField(auto_now=True, blank=True)
问题是如何最好地连接这两个表,以便用户配置文件字段可以与用户名一起在topic.html中显示?
发布于 2015-04-13 09:29:58
他们已经加入了。您可以通过my_topic.user.userprofile.name
等方式从主题到概要文件。
发布于 2015-04-13 09:34:02
由于Topic
模型从ForeignKey
到用户模型,在topic.html
中,您可以首先访问用户,然后访问它的配置文件:
{% with topic.creator as user %}
{% if user %}
<p>Username: {{ user.username }}</p>
<p>Email: {{ user.email }}</p>
{% with user.userprofile as profile %}
<p>Name: {{ profile.name }}</p>
<p>City: {{ profile.city }}</p>
<!-- More data here -->
{% endwith %}
{% endif %}
{% endwith %}
您可以阅读有关访问相关对象这里的更多信息。
https://stackoverflow.com/questions/29611108
复制相似问题