Created
July 2, 2013 19:43
-
-
Save keningle/5912470 to your computer and use it in GitHub Desktop.
Example of how to pass URL parameters to a decorator in Django
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.utils.functional import wraps | |
... | |
def check_company_admin(view): | |
@wraps(view) | |
def inner(request, slug, *args, **kwargs): | |
# Get the company object | |
company = get_object_or_404(Company, slug=slug) | |
# Check and see if the logged in user is admin | |
if company.admin_user != request.user: | |
return HttpResponseForbidden() | |
# Return the actual company object to the view | |
return view(request, company, *args, **kwargs) | |
return inner |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@login_required | |
@check_company_admin | |
def some_view(request, company): | |
# Even though the slug is in the URL. We are getting a company | |
# object back from the decorator | |
.... view logic .... | |
return render(request, 'company/index.html', {'company': company}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@login_required | |
def some_view(request, slug): | |
# Get the company object based on slug | |
company = get_object_or_404(Company, slug=slug) | |
# Check and see if the logged in user is admin | |
if company.admin_user != request.user: | |
return HttpResponseForbidden() | |
.... view logic .... | |
return render(request, 'company/index.html', {'company': company}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
url(r'^example/(?P<slug>[a-z0-9-]+)/$', 'some.view'), |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment