python - 在 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 模板中打印错误。
解决方案
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 %}
推荐阅读
- javascript - 过滤功能运行太晚了一步
- spring - 更改 OpenAPI 的自动生成 HomeController
- ios - SwiftUI:以编程方式关闭工作表
- java - 哪个 JSON 库允许通过 ID 反序列化对象?
- flutter - 为什么对话框打不开?
- spring-boot - @Aspect 不适用于“registerBeanDefinition”的动态 bean 注册
- winforms - 从 dll 或 xml 读取 RadSyntaxEditor 中的 Inteliprompts 数据
- reactjs - 开玩笑测试通过,但在运行开玩笑覆盖率时,我总是收到“渲染中没有返回任何内容”错误
- kubernetes - 删除部署中的一个 pod 后服务无法正常工作
- node.js - 嵌入响应时,它仅从随机选择 Discord.js 中返回 1 个集合答案