如何在 django 管理表单验证器中检测更新
我有一个用于 Post
模型中要使用的字段的自定义验证器 在管理界面中,验证器的目的是验证 没有其他帖子具有相同的 url
和 category
,但我找不到 区分更新或新帖子
的方式;在这种情况下 更新时,存在 post
不会有问题 相同的网址和类别。
这是验证器:
class MyPostAdminForm(forms.ModelForm):
class Meta:
model = Post
def clean_url(self):
url = self.cleaned_data['url']
# if doesn't have any category then
# just return the url to handle the error.
try:
cat = self.cleaned_data['category']
except KeyError:
return url
if UPDATE: # UPDATE???
#DON'T COMPLAIN IF IS THE SAME, RETURN THE URL
return url
else: # IS NEW!
try:
Post.objects.get(category=cat, url=url)
except Post.DoesNotExist:
return url
else:
raise forms.ValidationError('Already exists post with category "%s" and url "%s"'%(cat, url))
有什么想法吗?
I have a custom validator for a field in the Post
model to be used
in the admin interface, the purpose of the validator is to verify
that no other post has the same url
and category
, but I can't find
the way to distinguish from an update or a new Post
; which in the case
of an update it'll be no problem with the existence of a post
with
the same url and category.
Here is the validator:
class MyPostAdminForm(forms.ModelForm):
class Meta:
model = Post
def clean_url(self):
url = self.cleaned_data['url']
# if doesn't have any category then
# just return the url to handle the error.
try:
cat = self.cleaned_data['category']
except KeyError:
return url
if UPDATE: # UPDATE???
#DON'T COMPLAIN IF IS THE SAME, RETURN THE URL
return url
else: # IS NEW!
try:
Post.objects.get(category=cat, url=url)
except Post.DoesNotExist:
return url
else:
raise forms.ValidationError('Already exists post with category "%s" and url "%s"'%(cat, url))
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有必要这样做:如果您在模型的 Meta 类中设置
unique_together
,管理员将自动验证不存在具有相同组合的其他实例。但是,要回答一般性问题,判断这是否是更新的方法是检查 self.instance 是否存在并且具有 pk 字段的值。
There's no need to do this: if you set
unique_together
in your model's Meta class, the admin will automatically validate that no other instance exists with the same combination.However, to answer the general question, the way to tell if this is an update is to check that
self.instance
exists and has a value for thepk
field.