Created
December 20, 2012 09:38
-
-
Save jsanchezpando/4344176 to your computer and use it in GitHub Desktop.
Simple Django super class to track user and save creator and modifier of a Model.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from myapp.utils import set_current_user | |
class CurrentUserMiddleware: | |
def process_request(self, request): | |
set_current_user(getattr(request, 'user', None)) | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import models | |
from django.contrib.auth.models import User | |
from myapp.utils import get_current_user | |
class FollowUserModel(models.Model): | |
created_at = models.ForeignKey(auto_now_add=True) | |
modified_at = models.ForeignKey(auto_now=True) | |
created_by = models.ForeignKey(User, null=True, editable=False, related_name='%(class)s_created') | |
modified_by = models.ForeignKey(User, null=True, editable=False, related_name='%(class)s_modified') | |
def save(self, *args, **kwargs): | |
user = get_current_user() | |
if user and user.is_authenticated(): | |
self.modified_by = user | |
if not self.id: | |
self.created_by = user | |
super(FollowUserModel, self).save(*args, **kwargs) | |
class Meta: | |
abstract = True |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
MIDDLEWARE_CLASSES = ( | |
# ... | |
'myapp.middleware.CurrentUserMiddleware', | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import threading | |
_thread_locals = threading.local() | |
def set_current_user(user): | |
_thread_locals.user=user | |
def get_current_user(): | |
return getattr(_thread_locals, 'user', None) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@KrYpTeD974
are you able to provide your complete files? please