Django Permissions with CustomUser

Viewed 358

I'm trying to implement class Based views with permissions and they do not seem to connect, although I believe I strictly followed Django User's guide. First: set up of a Custom User model, based on Proxies, in accounts.models

class CustomUser(AbstractUser):
 some_fields...

Then, I created a Manager:

class EmployeeManager(models.Manager):
    def get_queryset(self, *args, **kwargs):
        return super().get_queryset(*args, **kwargs).filter(status_type=CustomUser.StatusType.EMPLOYEE)

Followed by the type of profile:

class Employee(CustomUser):
    objects = EmployeeManager()

    class Meta:
        proxy = True
        permissions = [("communities.view_region", "Can view region")]

Where I set a permission, make the migrations and migrate. After, I create the view:

import communities.models as comms

class RegionsListView(ListView):
    model = comms.Region

Then, configuration of the url and its view:

rom django.urls import path, include
import communities.views as views
from django.contrib.auth.decorators import permission_required

app_name = 'communities'

urlpatterns = [
    path("regions/list/", permission_required("communities.view_region")(views.RegionsListView.as_view()))

Then I log in as an employee and I get an error 403 when calling this url.

What did I miss ? Remarks:

  • using permission_required = 'communities.view_region' in the view.py file produces the same result.
  • when logging as a superuser, I get of course the right page.
1 Answers

In order to implement the permissions, it had to be done programmatically, while creating a new user. In the workflow,

  • the new User gets an activation e-mail with a unique link,
  • the click gives him access to the website and he is required to immediately change his password,
  • the validation implements the permission (in this case, a Group)

Here is the code.

from django.contrib import messages
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import PasswordChangeForm
from django.shortcuts import redirect, render
from django.contrib.auth.models import Group

@login_required
def change_password(request):
    if request.method == "POST":
        form = PasswordChangeForm(user=request.user, data=request.POST)
        if form.is_valid():
            user = form.save()
            # Attributes to a user a group depending on his status.
            user.groups.add(Group.objects.get(name=user.status_type))
            update_session_auth_hash(request, user)  # Important!
            messages.success(request, 'Your PWD has been changed')
            return redirect('change_password')
        else:
            messages.error(request, 'Please Correct the Error')
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'accounts/change_password.html', {'form': form})
Related