我有一个非常简单的 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()
我需要确保没有人在管理表单中输入结束日期之后的开始日期,因此我阅读了 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](https://i.stack.imgur.com/3pvc7.png)
我究竟做错了什么 ??
通常您只想在模型本身上定义一个 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")
类似的东西可以在 django admin 中工作,无需创建表单类。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)