Login

Get the referer view of a request

Author:
arthurfurlan
Posted:
April 28, 2009
Language:
Python
Version:
1.0
Tags:
view referer request path
Score:
1 (after 1 ratings)

Get the referer view of a request.

Example:

def some_view(request):
    ...
    referer_view = get_referer_view(request)
    return HttpResponseRedirect(referer_view, '/accounts/login/')
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# -*- coding: utf-8 -*-
#
# Copyright (c) 2009 Arthur Furlan <arthur.furlan@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# On Debian systems, you can find the full text of the license in
# /usr/share/common-licenses/GPL-2

import re

def get_referer_view(request, default=None):
    ''' 
    Return the referer view of the current request

    Example:

        def some_view(request):
            ...
            referer_view = get_referer_view(request)
            return HttpResponseRedirect(referer_view, '/accounts/login/')
    '''

    # if the user typed the url directly in the browser's address bar
    referer = request.META.get('HTTP_REFERER')
    if not referer:
        return default

    # remove the protocol and split the url at the slashes
    referer = re.sub('^https?:\/\/', '', referer).split('/')
    if referer[0] != request.META.get('SERVER_NAME'):
        return default

    # add the slash at the relative path's view and finished
    referer = u'/' + u'/'.join(referer[1:])
    return referer

More like this

  1. Get email and push on couchdb - Model by magik_cypress 3 years, 4 months ago
  2. Add Extra Headers to Test Client Requests by luftyluft 7 years ago
  3. Other approach of making middleware (by decorators) by diverman 4 years, 3 months ago
  4. A GET string modifier templatetag by cogat 6 years, 6 months ago
  5. Decorator that limits request methods by schinckel 5 years, 11 months ago

Comments

Please login first before commenting.