Django Custom模板标签&从数据库获取pk

时间:2011-12-21 12:22:09

标签: django

我有一个用户配置文件模型,包含用户(ForeignKey)和user_timezone(CharField)。在我的模板页面上有一个下拉框,让用户选择他们的时区,他们提交,一切正常。除了我必须硬编码pk的事实。我似乎无法弄清楚如何获得当前用户?

import pytz
import datetime
import time
from pytz import timezone
from django import template
from django.contrib.auth.models import User
from turnover.models import UserProfile
from django.shortcuts import get_object_or_404

register = template.Library()

class TimeNode(template.Node):
    def __init__(self, format_string):
        self.format_string = format_string

    def render(self, context):
        # Get the user profile and their timezone
        profile = UserProfile.objects.get(pk=99) #<------ Hard Coded--
        set_user_timezone = profile.user_timezone

        # Set the Timezone
        dt = datetime.datetime.fromtimestamp(time.time(), pytz.utc)
        get_timezone = pytz.timezone(u'%s' % set_user_timezone)
        profile_timezone = get_timezone.normalize(dt.astimezone(get_timezone)).strftime(self.format_string)
        return profile_timezone

    @register.tag(name="current_time")
    def current_time(parser, token):
        tag_name, format_string = token.split_contents()
        return TimeNode(format_string[1:-1])

2 个答案:

答案 0 :(得分:3)

request = context.get('request')
user = request.user

但你应该在设置中:

TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    'django.core.context_processors.request',
    ...
)

答案 1 :(得分:0)

class TimeNode(template.Node):
    def __init__(self, format_string, user):
        self.format_string = format_string
        self.user = template.Variable(user)

    def render(self, context):
        # Get the user profile and their timezone
        profile = UserProfile.objects.get(user=self.user) #<------ Hard Coded--
        set_user_timezone = profile.user_timezone

        # Set the Timezone
        dt = datetime.datetime.fromtimestamp(time.time(), pytz.utc)
        get_timezone = pytz.timezone(u'%s' % set_user_timezone)
        profile_timezone = get_timezone.normalize(dt.astimezone(get_timezone)).strftime(self.format_string)
        return profile_timezone

    @register.tag(name="current_time")
    def current_time(parser, token):
        tag_name, format_string, user = token.split_contents()
        return TimeNode(format_string[1:-1], user)

然后你可以做类似

的事情

{% current_time "timestring" request.user %}