DateField - “输入有效日期”消息

时间:2015-05-06 16:44:20

标签: django django-forms django-views

我有点困惑,为什么它一直返回'输入有效日期'的消息。这是我的格式吗?

我尝试了%m-%d-%Y的不同组合,但仍然没有运气。

models.py

class DeliveryDate(models.Model):
    cart = models.ForeignKey('Cart', null=True, blank=True)
    date = models.DateField()

    def __str__(self):
        return str(self.cart.id)
        return self.date

views.py

def add_delivery_date(request):

    the_id = request.session['cart_id']
    cart = Cart.objects.get(id=the_id)

    form = DeliveryDateForm(request.POST or None)

    if request.method == "POST":
        if form.is_valid():
            delivery_date = form.save(commit=False)
            date = request.POST['date']

            delivery_date = DeliveryDate.objects.create(cart=cart, date=date)
            delivery_date.save()

            return HttpResponseRedirect('thank-you.html')

    context = {
        "form": form
    }


    return render(request, 'choose_delivery_date.html', context)

forms.py

class DeliveryDateForm(forms.ModelForm):
    date = forms.DateField(input_formats=['%m %d %Y'], widget=SelectDateWidget, initial=datetime.date.today())

    class Meta:
        model = DeliveryDate
        fields = ['date']

1 个答案:

答案 0 :(得分:3)

首先在Django ModelForm中更改日期模型字段的小部件,而不添加额外的字段。 这是在__ init __方法中完成的:

from django.forms.extras.widgets import SelectDateWidget

class DeliveryDateForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(DeliveryDateForm, self).__init__(*args, **kwargs)
        #Change date field's widget here
        self.fields['date'].widget = SelectDateWidget()

    class Meta:
        model = DeliveryDate
        fields = ['date']

添加像你一样的字段:

class DeliveryDateForm(forms.ModelForm):
    date = forms.DateField(input_formats=['%m %d %Y'], widget=SelectDateWidget, initial=datetime.date.today())

实际上是在ModelForm中添加了一个额外的FormField,它与ModelField的名称相同。 这样,您只需将绑定日期ModelField小部件更改为3选择日/月/年

其次,您的表单验证是退出奇数: 我通常写的是这样的:

def add_delivery_date(request):

    the_id = request.session['cart_id']
    cart = Cart.objects.get(id=the_id)

    form = DeliveryDateForm()
    if request.method == "POST":
        form = DeliveryDate(data=request.POST)
        if form.is_valid():
            delivery_date = form.save(commit=False)
            delivery_date.cart = cart 
            delivery_date.save()
            return HttpResponseRedirect('thank-you.html')

    return render(request, 'choose_delivery_date.html', {
        'form': form
    })