4

I'm saving date in UTC. I wan't to change that date to automatic user timezone.

my settings

USE_TZ = True

my template

{% for sale in sales %}
    date : {{sale.date}}
{% endfor %}

I tried django-tz-detect

https://github.com/adamcharnock/django-tz-detect

but I can't implement that correctly.

Please suggest a good way to solve this issue.

4

1 回答 1

2

我从这里得到了解决方案

我创建了一个视图函数

@login_required 
@ajax_required
@require_GET
def set_user_timezone(request): 
    timezone = request.GET.get('timezone')
    request.session["set_user_timezone"] = timezone
    response_data = {}
    response_data['status'] = 'true'
    response_data['message'] = 'user timezone set successfully.'
    return HttpResponse(json.dumps(response_data), mimetype='application/javascript')

语境

if "set_user_timezone" in request.session:
    user_session_ok = True
    user_time_zone = request.session['set_user_timezone']
else:
    user_session_ok = False
    user_time_zone = "Asia/Kolkata"

在我的基本模板中

{% if not user_session_ok %}
    <script type="text/javascript" src="{% static 'js/jstz.js' %}"></script>
    <script>
        $(document).ready(function(){
             var timezone = jstz.determine();
             var timezone_name = timezone.name();
             $.ajax({
                url : '/set-user-timezone/',
                action : "GET",
                data : {
                    timezone : timezone_name
                },
                success : function(data){

                },
                error : function(data){

                }
             })
        });
    </script>
{% endif %}

我的销售模板

{% for sale in sales %}
    {% load tz %}                       
    date : {{ sale.sale_date|timezone:user_time_zone }}         
{% endfor %}

我不知道这是正确的方法。但这个解决方案对我有用。

于 2014-05-10T08:57:15.167 回答