gpt4 book ai didi

python - Django:删除/删除 slug

转载 作者:行者123 更新时间:2023-12-01 08:24:27 27 4
gpt4 key购买 nike

我正在处理的问题是表单错误“输入由字母、数字、下划线或连字符组成的有效‘slug’。”

以下是我的表单字段验证:

def clean_slug(self):
slug = self.cleaned_data['slug']
if slug.endswith('/'):
self.cleaned_data['slug'] = slug[:-1]
slug_check = self.organizer.events.filter(slug=slug).exclude(pk=self.event.pk).exists()
if slug_check:
raise forms.ValidationError(_("Slug already exists"), code='duplicated_slug')
return slug

不知何故,当调用 is_valid() 时,Django 没有考虑我的 self.cleaned_data['slug'] = slug[:-1]。你知道为什么吗?

最佳答案

您正在修改cleaned_data['slug'],这不会产生任何效果。 Django 将使用您从此方法返回的内容,并且您将返回原始(未修改的)slug。来自 documentation :

The return value of this method replaces the existing value in cleaned_data, so it must be the field’s value from cleaned_data (even if this method didn’t change it) or a new cleaned value.

将其更改为:

def clean_slug(self):
slug = self.cleaned_data['slug']
if slug.endswith('/'):
slug = slug[:-1] # <-- Modify slug, not cleaned_data['slug']
slug_check = self.organizer.events.filter(slug=slug).exclude(pk=self.event.pk).exists()
if slug_check:
raise forms.ValidationError(_("Slug already exists"), code='duplicated_slug')
return slug # <-- return modified value

关于python - Django:删除/删除 slug,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54373652/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com