【发布时间】:2015-03-24 23:59:11
【问题描述】:
请看一下这段代码:
型号:
class Activity(models.Model):
actor = models.ForeignKey(User)
action = models.CharField(max_length=100)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
pub_date = models.DateTimeField(auto_now_add=True, auto_now=False)
class Meta:
verbose_name = 'Activity'
verbose_name_plural = 'Activities'
ordering = ['-pub_date']
def __unicode__(self):
return ("%s %s") % (self.actor.username, self.action)
def get_rendered_html(self):
template_name = '%s_activity.html' %(self.content_type.name)
return render_to_string(template_name, {
'object':self.content_object,
'actor':self.actor,
'action':self.action,
})
模板:
<div class="user_activity">
<p><a href="/{{ actor.username }}/">{{ actor.username }}</a> {{ action }} <a href="/{{ object.content_object.user.username }}/">{{ object.content_object.user.username }}</a> status</p>
<p>{{ object.content_object.body }}</p>
<p>{{ object.content_object.pub_date }}</p>
{% if object.content_object.image %}
<div class="activity_img_wrapper">
<p><img src="/media/{{ object.content_object.image }}"/></p>
</div>
{% endif %}
</div>
问题
如何获取上述模板 (request.user) 的请求用户的用户名。我确实喜欢这个,但它没有帮助:
<div class="user_activity">
<p>
{% if user.username == actor.username %}
You
{% else %}
<a href="/{{ actor.username }}/">{{ actor.username }}</a>
{% endif %}
{{ action }}
{% if user.username == object.content_object.user.username %}
Your
{% else %}
<a href="/{{ object.content_object.user.username }}/">{{ object.content_object.user.username }}</a>
{% endif %}
status
</p>
<p>{{ object.content_object.body }}</p>
<p>{{ object.content_object.pub_date }}</p>
{% if object.content_object.image %}
<div class="activity_img_wrapper">
<p><img src="/media/{{ object.content_object.image }}"/></p>
</div>
{% endif %}
</div>
请帮助我如何做到这一点。我真的很感激你的帮助。谢谢。
【问题讨论】:
-
是的,我这样做了。但不工作。
标签: django django-models django-templates