Django admin中的自定义验证 [英] Custom validation in Django admin

查看:504
本文介绍了Django admin中的自定义验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的Django应用程序,用于记录同事们的演讲。由于它非常基础,所以我使用的是Django admin本身。这是我的models.py:

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:

#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()

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

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.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)

但是,这对我的管理员没有任何影响,并且我能够保存起始日期在end_date之后的讲座,如图所示:

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:

我在做什么错

推荐答案

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

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

这篇关于Django admin中的自定义验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆