Python Django admin 中的自定义验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24802244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:13:25  来源:igfitidea点击:

Custom validation in Django admin

pythondjangodjango-formsdjango-admindjango-validation

提问by Amistad

I have a very simple Django app in order to record the lectures given my colleagues.Since it is quite elementary,I am using the Django admin itself. Here is my models.py:

我有一个非常简单的 Django 应用程序,以便记录我同事的讲座。由于它非常初级,我正在使用 Django 管理员本身。这是我的models.py:

#models.py
from django.db import models

class Lecture(models.Model):
    topic = models.CharField(max_length=100)
    speaker = models.CharField(max_length=100)
    start_date = models.DateField()
    end_date = models.DateField()

I need to ensure that nobody enters the start date after the end date in the admin forms,so I read the django docs for custom validation in the admin and implemented the following in my admin.py:

我需要确保没有人在管理表单中的结束日期之后输入开始日期,所以我在 admin 中阅读了 django 文档以进行自定义验证,并在我的 admin.py 中实现了以下内容:

#admin.py
from models import Lecture
from django.contrib import admin
from django import forms


class LectureForm(forms.ModelForm):
    class Meta:
        model = Lecture

        def clean(self):
            start_date = self.cleaned_data.get('start_date')
            end_date = self.cleaned_data.get('end_date')
            if start_date > end_date:
                raise forms.ValidationError("Dates are incorrect")
        return self.cleaned_data


class LectureAdmin(admin.ModelAdmin):
    form = LectureForm
    list_display = ('topic', 'speaker', 'start_date', 'end_date')

admin.site.register(Lecture, LectureAdmin)

However,this has no effect whatsoever on my admin and I am able to save lectures where start_date is after end_date as seen in the image:enter image description here

但是,这对我的管理员没有任何影响,我可以保存开始日期在结束日期之后的讲座,如图所示:在此处输入图片说明

What am I doing wrong ??

我究竟做错了什么 ??

采纳答案by Daniel Roseman

You have an indentation issue. Your cleanmethod is indented within the form's Meta class. Move it back one level. Also, ensure that the returnstatement is indented within the method.

你有缩进问题。您的clean方法在表单的 Meta 类中缩进。将其移回一级。此外,确保return语句在方法中缩进。

回答by aris

Usually you just want to define a clean() method on the model itself.

通常你只想在模型本身上定义一个 clean() 方法。

https://docs.djangoproject.com/en/2.1/ref/models/instances/#validating-objects

https://docs.djangoproject.com/en/2.1/ref/models/instances/#validating-objects

from django.core.exceptions import ValidationError

class Lecture(models.Model):
    topic = models.CharField(max_length=100)
    speaker = models.CharField(max_length=100)
    start_date = models.DateField()
    end_date = models.DateField()

    def clean(self):
        if self.start_date > self.end_date::
            raise ValidationError("Dates are incorrect")

Something like that will work in the django admin without any need to create a form class.

类似的东西将在 django 管理员中工作,而无需创建表单类。