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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.