title: Change time zone depending on the user in django project
body: <p>I am trying to change the time zone in my project, depending on what the user has selected.</p>
  
  <p>To do that I have a field in my database, where I keep all possible locations:</p>
  
  <pre><code>timezone = models.CharField(max_length=40, null=True, blank=True, choices=[(n,n) for n in pytz.all_timezones])
  </code></pre>
  
  <p>but the problem is that when I try to change the time zone it does not work.</p>
  
  <p>---- setting.py ----</p>
  
  <pre><code>USE_TZ = True
  TIME_ZONE = 'Europe/Madrid'
  </code></pre>
  
  <p>---- Dashboard (view.py) ----> output</p>
  
  <pre><code>@login_required
  def dashboard(request):
      from datetime import datetime, timedelta    
      import pytz
  
      print "Normal:" + str(datetime.now()) # Normal:2018-04-19 08:39:51.484283
      print "TimeZone:" + str(timezone.now()) # TimeZone:2018-04-19 06:39:51.484458+00:00
  
      u = User.objects.get(user=request.user) # u: Alejandroid
      timezone_selected = u.timezone # timezone_selected: u'Canada/Saskatchewan'
      timezone.activate(pytz.timezone(timezone_selected))
  
      print "Normal:" + str(datetime.now()) # Normal:2018-04-19 08:40:02.829441
      print "TimeZone:" + str(timezone.now()) # TimeZone:2018-04-19 06:40:04.329379+00:00
  </code></pre>
  
  <hr>
  
  <p>As you can see, it only returns me the local time defined in TIME_ZONE and in UTC time.</p>
  
  <p>I'm working with Django 1.8</p>
  
  <p>How do I make it work?</p>
  
  <p>Thank you very much.</p>
  
  <hr>
  
  <hr>
  
  <p><strong>My solution</strong></p>
  
  <p>You need to create a middleware.</p>
  
  <pre><code>class TimezoneMiddleware(object):
  
      def process_request(self, request):
          from django.utils import timezone
          import pytz
          from settings import TIME_ZONE
              if request.user.is_authenticated():
                  timezone_selected = request.user.timezone
                  if not timezone_selected:
                      timezone_selected = TIME_ZONE
                  timezone.activate(pytz.timezone(timezone_selected))
              else:
                  timezone.deactivate()
  </code></pre>