Custom validation in Django admin(Django admin 中的自定义验证)
问题描述
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()
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)
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:
What am I doing wrong ??
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 中的自定义验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Django admin 中的自定义验证
基础教程推荐
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
