Django:限制可能的日期

时间:2015-11-09 11:46:51

标签: python django

我是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-admin界面中强制执行此条件?

2 个答案:

答案 0 :(得分:3)

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

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)

答案 1 :(得分:0)

您可以使用自定义模型表单(Model forms)并在保存之前验证数据,并在注册时执行类似

的操作
class TestAdmin(admin.ModelAdmin):
    form = ModelForm
    list_display = ('field1', 'field2')

admin.site.register(Lecture, LectureAdmin)