Login

decorator to add author to extra_fields in snippets 635

Author:
gehel
Posted:
May 12, 2008
Language:
Python
Version:
.96
Tags:
newforms decorator create_update author
Score:
0 (after 0 ratings)

I had the need to add request.user to the extra_fields argument of quite a few of my view based on create_update for newforms snippet. I could have wraped the create_object function in my views.py, but as the logic is always the same, it seemed like a good idea to Not Repeat Myself.

 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
from functools import wraps

def extra_author_field(view):
    """
    This decorator should be used in conjunction with the newforms
    create_update views. It adds "request.user" in the "extra_fields" dict.
    """
    @wraps(view)
    def wrapper(*args, **kwargs):
        request = args[0]
        kwargs.setdefault('extra_fields', {}).update({'author' : request.user})
        return view(*args, **kwargs)
    return wrapper



#### urls.py (extract only) ####

"""This decorator can be used as shown below"""

url(r'^add/$',
    # here we use both the permission_required and my new extra_author_field decorator
    permission_required('news.add_news')(extra_author_field(create_object)),
    {
        'model' : News,
        'model_form' : NewsForm,
        'login_required' : True,
    },
),

More like this

  1. IP Authorization Decorator with IP list by jansta 4 years, 3 months ago
  2. @url decorator improvements by davepeck 5 years, 9 months ago
  3. FilterSpec for ForeignKeys to auth.User with HTML input tag for ModelAdmin.list_filter by loic 4 years ago
  4. Authentication Against Active Directory (LDAP) over SSL by mary 6 years, 10 months ago
  5. Anticollate? Disinterleave? by lemonlaug 5 years, 4 months ago

Comments

Please login first before commenting.