sissbruecker / linkding

Self-hosted bookmark manager that is designed be to be minimal, fast, and easy to set up using Docker.
MIT License
5.32k stars 261 forks source link

Add timezone option to UserProfile model #722

Open trey opened 2 months ago

trey commented 2 months ago

It would be nice to be able to set your preferred timezone in the settings page. I wouldn't have noticed its absence without the nice, new View bookmark modal!

I implemented a timezone picker in Cassette Nest (also a Django app) something like this:

⭐ Install pytz

⭐ Add some things to settings.py:

from pytz import common_timezones

# ... other stuff

MIDDLEWARE = [
    "your_app.middleware.TimezoneMiddleware",
]

# ... other stuff

TIME_ZONES = [(tz, tz) for tz in common_timezones]

⭐ Create the timezone middleware:

import pytz
from django.utils import timezone
from django.conf import settings

class TimezoneMiddleware:
    """
    Automatically set the timezone to what's set on the User's profile.
    """

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if request.user.is_authenticated:
            try:
                tzname = request.user.profile.timezone
                if tzname:
                    timezone.activate(pytz.timezone(tzname))
                else:
                    timezone.activate(pytz.timezone(settings.TIME_ZONE))
            except Profile.DoesNotExist:
                timezone.activate(pytz.timezone(settings.TIME_ZONE))
        else:
            timezone.deactivate()

        return self.get_response(request)

⭐ Add this to my profile model:

from django.conf import settings

# other stuff ...

timezone = models.CharField(
    max_length=40,
    blank=True,
    choices=settings.TIME_ZONES,
    default=settings.TIME_ZONE,
)

⭐ And add the field to the ModelForm.

I'd be happy to help implement this if you want it done! 😄

I should note that my user profile model is just called Profile, but that's a minor difference.