Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add timezone option to UserProfile model #722

Open
trey opened this issue May 3, 2024 · 0 comments
Open

Add timezone option to UserProfile model #722

trey opened this issue May 3, 2024 · 0 comments

Comments

@trey
Copy link

trey commented May 3, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant