验证 django-admin 内联表单上的删除
我正在尝试执行验证,以便您无法删除用户(如果他是管理员)。因此,我想检查是否存在管理员用户并已被标记为删除,并提出错误。
这是我的内联 ModelForm
class UserGroupsForm(forms.ModelForm):
class Meta:
model = UserGroups
def clean(self):
delete_checked = self.fields['DELETE'].widget.value_from_datadict(
self.data, self.files, self.add_prefix('DELETE'))
if bool(delete_checked):
#if user is admin of group x
raise forms.ValidationError('You cannot delete a user that is the group administrator')
return self.cleaned_data
if bool(delete_checked): 条件返回 true,并且 if
块内的内容被执行,但由于某种原因此验证永远不会引发错误。有人可以向我解释一下为什么吗?
更好的是,如果有其他更好的方法来做到这一点,请告诉我
I am trying to perform a validation such that you cannot delete a user if he's an admin. I'd therefore like to check and raise an error if there's a user who's an admin and has been marked for deletion.
This is my inline ModelForm
class UserGroupsForm(forms.ModelForm):
class Meta:
model = UserGroups
def clean(self):
delete_checked = self.fields['DELETE'].widget.value_from_datadict(
self.data, self.files, self.add_prefix('DELETE'))
if bool(delete_checked):
#if user is admin of group x
raise forms.ValidationError('You cannot delete a user that is the group administrator')
return self.cleaned_data
The if bool(delete_checked):
condition returns true and stuff inside the if
block gets executed but for some reason this validation error is never raised. Could someone please explain to me why?
Better yet if there's another better way to do this please let me know
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我找到的解决方案是在
InlineFormSet
而不是ModelForm
中进行clean
The solution I found was to
clean
in theInlineFormSet
instead of theModelForm
添加到多米诺骨牌的答案:
在其他一些场景中,有时用户希望同时删除和添加对象,所以在这种情况下删除应该没问题!
优化版本代码:
Adding to domino's Answer:
In some other scenarios, Sometimes user wants to delete and add object in the same time, so in this case delete should be fine!
Optimized version of code:
虽然@domino的答案目前可能有效,但“有点” 推荐的方法是将formset的
self._should_delete_form(form)
函数与self.can_delete
一起使用。还有调用
super().clean()
来执行标准内置验证的问题。所以最终的代码可能如下所示:Although @domino's answer may work for now, the "kinda" recommended approach is to use formset's
self._should_delete_form(form)
function together withself.can_delete
.There's also the issue of calling
super().clean()
to perform standard builtin validation. So the final code may look like: