我有表格(感谢Alasdair):
class PermissionsModelMultipleChoiceField(forms.ModelChoiceField):
def label_from_instance(self, obj):
return "%s" % obj.name
class UserForm(forms.ModelForm):
first_name = forms.CharField(label=u'First name', required=True)
last_name = forms.CharField(label=u'Last name', required=True)
permissions = PermissionsModelMultipleChoiceField(Permission.objects.none(), widget=forms.CheckboxSelectMultiple)
def __init__( self, *args, **kwargs ):
super( NewUserForm, self ).__init__( *args, **kwargs )
ctypes = ContentType.objects.filter(
Q(app_label='articles') |
Q(app_label='tags')
)
self.fields['permissions'].queryset = Permission.objects.filter(content_type__in=ctypes)
class Meta:
model = User
在模板权限中显示我的权限:
[] Can change article
[] Can delete article
[] Can view article
[...]
致电表格:
profile_user = User.objects.get(pk=user_id)
if request.method == 'POST':
form = UserForm(request.POST, instance=profile_user)
if form.is_valid():
form.save()
[... here will save permissions ...]
return HttpResponseRedirect(reverse('home'))
else:
form = UserForm(instance=profile_user)
如何在模板中设置分配给已编辑用户的权限?
答案 0 :(得分:1)
在实例化表单时(仅在data
请求之外),使用参数POST
填充复选框,如下所示:
profile_user = User.objects.get(pk=user_id)
if request.method == 'POST':
form = UserForm(request.POST, instance=profile_user)
if form.is_valid():
form.save()
[... here will save permissions ...]
return HttpResponseRedirect(reverse('home'))
else:
user_permissions_list = # place here the query to get the profile_user permissions
form = UserForm(instance=profile_user, data={'permissions':user_permissions_list})
使用data
是根据用户实际权限标记复选框的关键。
希望它有所帮助!