Skip to content

Instantly share code, notes, and snippets.

@keningle
Created July 2, 2013 19:43
Show Gist options
  • Save keningle/5912470 to your computer and use it in GitHub Desktop.
Save keningle/5912470 to your computer and use it in GitHub Desktop.
Example of how to pass URL parameters to a decorator in Django
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
@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})
@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})
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