改善这段代码,在每个功能要有勾选,添加用户群组的下拉框,实现通过勾选权限赋予选择的用户群组
时间: 2023-12-16 18:04:48 浏览: 88
假设你的代码是基于 Django 的,可以参考下面的实现:
在模型中定义用户组:
```python
from django.contrib.auth.models import Group
class Permission(models.Model):
# 权限相关的字段
group = models.ForeignKey(Group, on_delete=models.CASCADE)
# ...
```
在表单中添加用户组选择框:
```python
from django import forms
from django.contrib.auth.models import Group
class PermissionForm(forms.ModelForm):
class Meta:
model = Permission
fields = ['group', ...]
group = forms.ModelChoiceField(
queryset=Group.objects.all(),
widget=forms.CheckboxSelectMultiple,
label='用户组'
)
# ...
```
在视图中处理表单:
```python
from django.shortcuts import render, redirect
from .forms import PermissionForm
def create_permission(request):
if request.method == 'POST':
form = PermissionForm(request.POST)
if form.is_valid():
permission = form.save(commit=False)
# 根据选择的用户组授权
group = permission.group
group.permissions.add(permission)
group.save()
return redirect('permission-list')
else:
form = PermissionForm()
return render(request, 'create_permission.html', {'form': form})
```
这里假设一个权限只能赋予给一个用户组,如果需要支持多个用户组,可以将 `ForeignKey` 改为 `ManyToManyField`。
阅读全文