django - 通过模型方法在模板中获取请求的用户对象

django - getting the requested user object in the template through models method

请看一下这段代码:

型号:

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>

请帮我看看怎么做。我真的很感激你的帮助。谢谢。

get_rendered_html() 方法中没有可用的 RequestContext 对象,因此您不能将其作为 render_to_string()context_instance 参数传递。这就是 user 变量在模板中不可用的原因。

您应该将 User 实例传递给 get_rendered_html() 方法并将其传播到模板:

def get_rendered_html(self, user=None):
    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,
        'user':user,
    })

如果你想从其他模板调用这个方法,那么最好的选择是使用 custom template tag:

# app/templatetags/activity_tags.py
# and don't forget to create empty app/templatetags/__init__.py :-)
from django import template
from django.utils.safestring import mark_safe

register = template.Library()

@register.simple_tag(takes_context=True)
def render_activity(context, activity):
    user = context['user']
    html = activity.get_rendered_html(user)
    return mark_safe(html)

然后在您的模板中加载并使用此标签库:

{% load activity_tags %}
...
{% render_activity activity %}