0

I have to refactor code which is like:

views.py

def some_method(request):
    customers = list()
    if request.session['group'] == "group1":
        foo = foo.objects.filter(blue=True)
    else:
        foo = foo.objects.all()

I have a lot of if else statements that I want to reduce using django builtin permissions, auth functionality. Any help ?

ekad
  • 14,436
  • 26
  • 44
  • 46
Waqas Javed
  • 743
  • 8
  • 18
  • possible duplicate of [User groups and permissions](http://stackoverflow.com/questions/12393726/user-groups-and-permissions) – Glyn Jackson Dec 08 '14 at 13:48

1 Answers1

0

I recommend you to read: Using the Django authentication system, and specialy the section: The permission_required decorator.

There you will find that you could refactor your function like this:

@permission_required('some.permission.only.group1.has')
def some_method(request):
    customers = list()
    foo = foo.objects.filter(blue=True)

For the case the user isn't in the group1 should exist another view. The example you posted don't really ilustrates the need for having a view for each case, but believe me it will make your life easier.

A Tip: In templates you can restrict what the user sees using permissions as well. You might manage permissions even before the view get called.

{% if perms.app_label.can_do_something %}
<form here>
{% endif %}

The currently logged-in user's permissions are stored in the template variable {{ perms }}

References: Check permission inside a template in Django

Community
  • 1
  • 1
Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60