2011-12-21 10 views
0

私はuser(ForeignKey)とuser_timezone(CharField)を持つユーザープロファイルモデルを持っています。私のテンプレートページには、ユーザーが自分のタイムゾーンを選択できるようにするドロップダウンボックスがあり、すべて送信されます。私はpkをハードコードする必要があるという事実を除いて。私は現在のユーザーを取得する方法を把握していないようですか?Djangoカスタムテンプレートタグ&データベースから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]) 

答えて

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

しかし、あなたが設定している必要があります

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

ような何かを行うことができ、私はどのように確認されませんでした要求を渡す。 2日間の太陽の下ですべてを試した後、2行のコードが短くなりました。少ないほうがいいですね。 – Dunwitch

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 %}

関連する問題