【问题标题】:django form not validating the datefielddjango 表单不验证日期字段
【发布时间】:2015-01-15 16:10:40
【问题描述】:

我有一个表格:

class AppointmentForm1(forms.Form):

f_name = forms.CharField(max_length=100)
appointment_date = forms.DateField()

def clean_appointment_date(self):
    appointment_date = self.cleaned_data['appointment_date']
    today = date.today()
    next_week = today + timedelta(days=7)
    if appointment_date is None:
        raise forms.ValidationError("You must provide a date to take appointment")
    if appointment_date < today:
        raise forms.ValidationError("You cannot take appointment on past date")
    if appointment_date > next_week:
        raise forms.ValidationError("You can only take appointment with in one week")
    return appointment_date

我已经看到了约会日期..

appointment_date = request.GET.get('appointment_date')
app = DoctorAppointment()
app.appointment_date = appointment_date
app.save()

我有一个名为 DoctorAppointment 的模型。 当我这样做并输入约会日期的任何值时,它会保存在数据库中。它没有显示任何错误。

在我的模板中我已经完成了:

{{ form.appointment_date.errors }}
{{ appointment_form.appointment_date }}

我在验证日期字段时做错了什么吗? today = date.today() next_week = today + timedelta(days=7) 的值是正确的,我已在控制台中打印。

我的约会日期数据库是:

appointment_date = models.DateField()

需要帮助吗? 提前谢谢..

【问题讨论】:

  • 你为什么要对视图中的appointment_date 做任何事情?您已经通过表单对其进行验证...
  • 我只是将它保存到我认为的模型中..根本没有做任何事情..
  • 你能把你的整个视图包括在上面吗?查看保存它的时间/位置会很有帮助。
  • 为什么不用modelform?
  • 我不是 100% 确定问题是什么。您的代码是否有问题,或者您是否在询问是否有没有考虑到的边缘情况?

标签: python django forms validation


【解决方案1】:

您已声明表单AppointmentForm1,但没有使用它

appointment_date = request.GET.get('appointment_date')

当您尝试在数据库中创建/更新数据时使用 POST

<form method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit">
</form>

所以在你看来应该是这样的

if request.POST:
    my_form = AppointmentForm1(request.POST)
    if my_form.is_valid():
        appointment_date = my_form.cleaned_data['appointment_date']
        DoctorAppointment.objects.create(appointment_date=appointment_date)

        return HttpResponseRedirect('some_url')
else:
    my_form = AppointmentForm1()

return render(request, 'some_app_name/some_html_name.html', {"form": my_form},
    content_type="application/xhtml+xml")

【讨论】:

    猜你喜欢
    • 2014-07-26
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 2012-05-06
    • 2019-06-03
    相关资源
    最近更新 更多