在 Django 模板中设置组

Set the groups in Django template

我想通过模板注册用户,我还想在注册的时候,为每个创建的新用户设置组(Django提供的默认组权限),我在模板中设置了用户组但是当我查看数据库中的用户组时,我发现它是空的。

class ProfileUserManager(BaseUserManager):

def create_user(self, username, password,**extra_fields):

    user = self.model(username=username, **extra_fields)
    user.set_password(password)
    user.save()
    return user

def create_superuser(self, username, password,**extra_fields):

    extra_fields.setdefault('is_staff', True)
    extra_fields.setdefault('is_superuser', True)
    extra_fields.setdefault('is_active', True)

    if extra_fields.get('is_staff') is not True:
         raise ValueError(_('Superuser must have is_staff=True.'))
    if extra_fields.get('is_superuser') is not True:
        raise ValueError(_('Superuser must have is_superuser=True.'))
    return self.create_user(username,password,**extra_fields)

class ProfileUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(default=timezone.now)
username = models.CharField(max_length=255,unique=True)
first_name=models.CharField(max_length=255)
last_name= models.CharField(max_length=255)
departement= models.CharField(max_length=255)


USERNAME_FIELD = 'username'
REQUIRED_FIELDS = []

objects = ProfileUserManager()


def __str__(self):
    return self.username

forms.py

class FormAddAccount(UserCreationForm):

class Meta(UserCreationForm.Meta):
    model = get_user_model()
    fields = ('email', 'password1', 'password2', 'is_staff','username','groups','first_name','last_name','departement')

首先,您在应用程序中创建 decoratorsy.py,然后在 decorators.py

中添加以下代码
from django.http import HttpResponse
from django.shortcuts import redirect


def unauthenticated_user(view_func):
  def wrapper_func(request, *args, **kwargs):
    if request.user.is_authenticated:
        return redirect('url')
    else:
        return view_func(request, *args, **kwargs)

return wrapper_func


 def allowed_users(allowed_roles=[]):
   def decorator(view_func):
    def wrapper_func(request, *args, **kwargs):

        group = None
        if request.user.groups.exists():
            group = request.user.groups.all()[0].name

        if group in allowed_roles:
            return view_func(request, *args, **kwargs)
        else:
            return HttpResponse('You are not authorized to view this page')

    return wrapper_func

return decorator


  def admin_only(view_func):
    def wrapper_function(request, *args, **kwargs):
        group = None
    if request.user.groups.exists():
        group = request.user.groups.all()[0].name

    if group == 'GroupName':
        return redirect('url')


    if group == 'admin':
        return view_func(request, *args, **kwargs)

return wrapper_function

views.py

def createuser(request):
form = CreateUserForm()
if request.method == 'POST':
    form = CreateUserForm(request.POST)
    if form.is_valid():
        form.save()
        user = form.save()
        username = form.cleaned_data.get('username')
        group = Group.objects.get(name='GroupName')
        user.groups.add(group)
        Customer.objects.create(
            user=user, )

        messages.success(request, 'Account was created for ' + username)

        return redirect('login')

context = {'form': form}
return user

在你的 views.py 上添加 @allowed_users(allowed_roles=['GROUPNAME']) 为了获得许可,该组看到以下内容

我只是在添加用户时向 Views.py 添加了一些代码行:

def createView(request):
form=FormAddAccount()
if request.method=="POST":
    form=FormAddAccount(request.POST)
    if form.is_valid():
        user=form.save()
        for element in form.cleaned_data["groups"] :
            group = Group.objects.get(name=element)
            user.groups.add(group)
        user.save()
        redirect("accounts/list.html")
context={
    'form':form
}

return render(request,"accounts/addaccount.html",context)