首页 > 解决方案 > 在 Django 的提交表单中获取错误的格式输入(日期时间格式)时如何打印错误?

问题描述

我正在 Web 浏览器上构建应用程序流对象检测,数据(日期时间、对象信息等)保存在 mysql 数据库中,该应用程序有一个用于根据日期时间过滤数据的网页,现在它仅在格式是正确的日期时间格式(例如 2019-07-24 12:00:00),如果不正确(例如 2019-07-123),Web 浏览器将返回错误页面。 在此处输入图像描述

搜索.html

<input id="from_date" type="text" name="from_date" placeholder="From Date...">
<input id="to_date" type="text" name="to_date" placeholder="To Date...">

视图.py

def search(request):
    if request.method == 'GET':
        from_date = request.GET.get('from_date')
        to_date = request.GET.get('to_date')

        "code to detect if from_date and to_date are incorrect formats???"

我想知道如何检测这种情况,然后在我的 Web 模板中打印错误。

标签: pythonhtmlmysqldjango

解决方案


Django 提供forms,其中DateTimeField可以处理日期时间格式问题。

不过,如果您想使用现有代码,则可以执行以下实现:

import datetime

def search(request):
    if request.method == 'GET':
        from_date = request.GET.get('from_date')
        to_date = request.GET.get('to_date')
        input_formats = [
            '%y-%m-%d %H:%M',
            '%y-%m-%d',
         ]
         from_date_validated = None
         to_date_validated = None

         for format in input_formats:
            try:
                from_date_validated = datetime.datetime.strptime(from_date, format)
            except (ValueError, TypeError):
                continue
            try:
                to_date_validated = datetime.datetime.strptime(to_date, format)
            except (ValueError, TypeError):
                continue
         if not to_date_validated or not from_date_validated:
             return render(request, 'error_page.html', context={'to_date_validated': to_date_validated, 'from_date_validated': from_date_validated})

并更新模板:

{% if not to_date_validated %}
    Please enter proper to date
{% else %}
   Please enter proper from date
{% endif %}

推荐阅读