0

I have customized user profiles in Wagtail by adding fields (drm, cpm). How can I modify the form, or more specifically, the values in the form's lists based on the currently logged-in user and their permissions?

Hello everyone, I have customized user profiles in Wagtail by adding fields (drm, cpm). How can I modify the form, or more specifically, the values in the form's lists based on the currently logged-in user and their permissions?

For example, let's say you have extended the user profile model in Wagtail to include custom fields drm and cpm, and you want to dynamically populate a choice field in a form based on the user's role or permissions. Here's how you might approach this:

# in models.py

from django.db import models
from wagtail.users.models import UserProfile

class CustomUserProfile(UserProfile):
    drm = models.CharField(max_length=50, blank=True, null=True)
    cpm = models.CharField(max_length=50, blank=True, null=True)


Next, you can create a custom form for a Wagtail admin page and override the form fields based on the user's profile:

# in admin.py

from wagtail.contrib.modeladmin.options import ModelAdmin
from wagtail.contrib.modeladmin.views import CreateView, EditView
from wagtail.contrib.modeladmin.helpers import PermissionHelper
from .models import CustomUserProfile

class CustomUserProfilePermissionHelper(PermissionHelper):
    def user_can_edit_obj(self, user, obj):
        # Customize this method to check if the user has permission to edit this profile
        return True  # For demonstration purposes, allowing all users to edit

class CustomUserProfileEditView(EditView):
    permission_helper_class = CustomUserProfilePermissionHelper

    def get_form(self):
        form = super().get_form()

        user = self.request.user

        if user.is_superuser:
            form.fields['drm'].choices = [('admin', 'Administrator'), ('user', 'User')]
        else:
            form.fields['drm'].choices = [('user', 'User')]

        return form
modeladmin_register(CustomUserProfileEditView)

0 Answers0