Skip to content

Instantly share code, notes, and snippets.

@keningle
Created July 2, 2013 19:43
Show Gist options
  • Select an option

  • Save keningle/5912470 to your computer and use it in GitHub Desktop.

Select an option

Save keningle/5912470 to your computer and use it in GitHub Desktop.

Revisions

  1. keningle created this gist Jul 2, 2013.
    17 changes: 17 additions & 0 deletions decorator.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,17 @@
    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
    9 changes: 9 additions & 0 deletions new_view.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,9 @@
    @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})
    12 changes: 12 additions & 0 deletions orginial_view.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,12 @@
    @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})
    1 change: 1 addition & 0 deletions url.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    url(r'^example/(?P<slug>[a-z0-9-]+)/$', 'some.view'),