我有形式(感謝阿拉斯代爾):如何在編輯用戶表單中檢查權限?
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)
如何設定檢查模板這是分配給編輯的用戶的權限?
我不太明白,如果用戶具有該特定權限,您希望將複選框顯示爲** checked **。 –
是的,例如,如果用戶有「可以查看文章」的提示,我想檢查這個複選框 – Nips