gpt4 book ai didi

python - Django:限制可能的日期

转载 作者:行者123 更新时间:2023-11-30 23:04:36 25 4
gpt4 key购买 nike

我是 Django 新手。我正在使用 Django 1.8 和 Python 3.4。

class Card(models.Model):
STATUS_EXPIRED = "EX"
STATUS_ACTIVE = "AC"
STATUS_DEACTIVATED = "DE"
STATUS_CHOICES = (
(STATUS_ACTIVE, "Active"),
(STATUS_EXPIRED, "Expired"),
(STATUS_DEACTIVATED, "Deactivated")
)

id = models.AutoField(primary_key = True)
series = models.CharField(verbose_name="Series", max_length=8, null=False, blank=False)
number = models.CharField(verbose_name="Number", max_length=16, null=False, blank=False)
issue_date = models.DateTimeField(verbose_name="Issue Date", auto_now=True, null=False, blank=False)
expire_date = models.DateTimeField(verbose_name="Expiry Date", auto_now=False, null=False, blank=False)
status = models.CharField(verbose_name="Status", max_length=3, null=False, blank=False, default="AC")

如何确保数据库中的 expire_date 永远不会小于 issue_date?创建 Card 类的对象时,如何在 Django 管理界面中强制执行此条件?

最佳答案

您可以像这样在管理中进行表单验证;

from models import Card
from django.contrib import admin
from django import forms


class CardForm(forms.ModelForm):
class Meta:
model = Card
fields = ('series', 'number', 'issue_date', 'expire_date', 'status')

def clean(self):
issue_date = self.cleaned_data.get('issue_date')
expire_date = self.cleaned_data.get('expire_date')
if expire_date < issue_date:
raise forms.ValidationError("Wrong dates")
return self.cleaned_data


class CardAdmin(admin.ModelAdmin):
form = CardForm
list_display = ('series', 'number', 'issue_date', 'expire_date', 'status')

admin.site.register(Card, CardAdmin)

关于python - Django:限制可能的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33608417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com