在 Django 管理中,如何将博客文章设置为仅验证它是否是草稿?

发布于 2024-10-09 15:55:27 字数 286 浏览 0 评论 0原文

我正在为 Django 开发一个博客,我想使用 Django 管理员的内置验证。但是,如果博客文章状态设置为“草稿”,我想要某种方法来禁用验证。

基本上,我正在寻找应该执行以下操作的代码:

def validate(self, **kwargs):
    ''' do not validate drafts '''
    if self.status != Post.STATUS_DRAFT:
        Super(Post, self).validate(**kwargs)

I'm working on a blog for Django, and I would like to use the Django admin's built in validation. However, I would like some way to disable validation if the blog post status is set to "draft".

Basically, I'm looking for code that should do something like this:

def validate(self, **kwargs):
    ''' do not validate drafts '''
    if self.status != Post.STATUS_DRAFT:
        Super(Post, self).validate(**kwargs)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

巴黎盛开的樱花 2024-10-16 15:55:27

您不能验证表单。例如,表单验证的作用是确保应包含数字的值包含数字。您认为帖子处于“草稿”模式这一事实并不能成为日期字段必须包含日期而不是无意义文本字符串的借口。

我想您想要的是允许某些字段在正常模式下是必需的,但在草稿模式下是可选的。

在这种情况下,这是在模型级别完成的。您可以使用自定义管理表单来强制执行此行为:

# models.py
...
class Post(models.Model):
    title = models.CharField(..., null=True, blank=True)
    fliddle = models.IntegerField(..., null=True, blank=True)
    published = models.BooleanField() # if false, then in draft mode


# admin.py
...
class BlogForm(forms.ModelForm):
    class Meta:
        model = Post

    title = forms.CharField(..., required=False)
    fliddle = forms.IntegerField(..., required=False)

    def __init__(self, *args, **kwargs):
        self.instance = kwargs.get('instance', None)
        super(BlogForm, self).__init__(*args, **kwargs)

    def clean_title(self):
        data = self.cleaned_data.get('title',None)
        if self.instance and self.instance.published == True and not data:
            raise forms.ValidationError("Title is required.")
        return data

    def clean_fliddle(self):
        data = self.cleaned_data.get('fliddle',None)
        if self.instance and self.instance.published == True and not data:
            raise forms.ValidationError("Fliddle is required.")
        return data

class BlogAdmin(admin.ModelAdmin):
    class Meta:
        model=Blog
    form = BlogForm

admin.site.register(Blog, BlogAdmin)

You can't not validate forms. The role of form validation is to make sure that, for example, a value that should contain a number contains a number. The fact that you believe the post to be in "draft" mode does not excuse the necessity of a date field to contain a date rather than a string of meaningless text.

I imagine what you want is to allow certain fields to be required in normal mode, but optional in draft mode.

In which case, this is done on the model level. You can use a custom admin form to enforce this behavior:

# models.py
...
class Post(models.Model):
    title = models.CharField(..., null=True, blank=True)
    fliddle = models.IntegerField(..., null=True, blank=True)
    published = models.BooleanField() # if false, then in draft mode


# admin.py
...
class BlogForm(forms.ModelForm):
    class Meta:
        model = Post

    title = forms.CharField(..., required=False)
    fliddle = forms.IntegerField(..., required=False)

    def __init__(self, *args, **kwargs):
        self.instance = kwargs.get('instance', None)
        super(BlogForm, self).__init__(*args, **kwargs)

    def clean_title(self):
        data = self.cleaned_data.get('title',None)
        if self.instance and self.instance.published == True and not data:
            raise forms.ValidationError("Title is required.")
        return data

    def clean_fliddle(self):
        data = self.cleaned_data.get('fliddle',None)
        if self.instance and self.instance.published == True and not data:
            raise forms.ValidationError("Fliddle is required.")
        return data

class BlogAdmin(admin.ModelAdmin):
    class Meta:
        model=Blog
    form = BlogForm

admin.site.register(Blog, BlogAdmin)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文