The Django Analytics middleware employs a user proxy class to collect information about the user making each request. By overriding this class with your own implementation you can customize what data gets collected. This can also be useful if your site is using a non-standard User model instead of the one built into Django.
Here is a sample implementation of the user proxy class:
class UserProxy(object):
def is_logged_in(self, request):
# Returns True if the request belongs to a user who's logged in.
# If False is returned, all other methods will not be called.
return hasattr(request, 'user') and request.user.is_authenticated()
def get_id(self, request):
# Returns a unique identification number for the user.
return request.user.id
def get_username(self, request):
# Returns the username (optional)
return request.user.username
def get_full_name(self, request):
# Returns the user's full name (optional)
return request.user.get_full_name()
def get_email(self, request):
# Returns the user's email address (optional)
return request.user.email
def get_tags(self, request):
# Returns a list user tags
return ['staff'] if request.user.is_staff else []
def get_date_joined(self, request):
# Returns the user's registration date
return request.user.date_joined
To override the user proxy class, extend the default implementation (da_tracker.middleware.UserProxy) and provide the custom class name in your settings file:
DJANGO_ANALYTICS_USER_PROXY = 'example.userproxy.MyUserProxy'
Check out the examples below to see how this can be useful.
You can use a custom user proxy to prevent names and emails from being tracked by Django Analytics:
from da_tracker.middleware import UserProxy
class AnonymizingUserProxy(UserProxy):
def get_full_name(self, request):
return None
def get_email(self, request):
return None
Let's say you have a user profile model that can tell you whether the user paid for your application. You can use this information to add a "paid" tag to such users:
from da_tracker.middleware import UserProxy
class TaggingUserProxy(UserProxy):
def get_tags(self, request):
tags = super(TaggingUserProxy, self).get_tags(request)
if request.user.get_profile().is_paying():
tags.append('paid')
return tags