Question

I'd like to save the site that a user came from when they sign up. I am interested in the HTTP referer of the first page the user saw on my site before signing up.

How can I implement it?

Was it helpful?

Solution

First, save the referrer to the session. You should probably do this in some kind of middleware:

import urlparse

class SaveReferrerMiddleware(object):
    def process_request(self, request):
        referer = request.META.get('HTTP_REFERER', None)
        if referer is not None:
            domain = urlparse.urlparse(referer).netloc
            if domain not in ['www.yoursite.com', 'yoursite.com']:
                # External referer
                request.session['initial_referer'] = referer

(Obviously, change yoursite.com etc. as appropriate)

Then, in your signup view code, save the referer from the session to your user object.

This will, of course, depend on having somewhere to store that info. If you have a custom user object, you can create a field for it. Before Django 1.5, you can use AUTH_PROFILE_MODULE to extend the user class. See https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top