我正在使用一个日期时间选择器,用户在其中选择一个月(MonthPickerInput)。
models.py
birthdayMonth = models.DateField(null=True, default=now)
表格
from bootstrap_datepicker_plus import MonthPickerInput
class QuestionForm(forms.ModelForm):
widgets = {
'birthdayMonth': MonthPickerInput(
options={
"showClose": False,
"showClear": False,
"showTodayButton": False,
}
),
}
用户单击表单字段,下拉日历,然后选择月份和年份。MonthPicker自动将日期设置为“ 1”。这在后端很好,但是在前端(以用户填写的形式),它像这样显示2020-03-01
。我希望它像这样显示March 2020
(03-2020也可以)。要做到这一点,我添加一个字段format
中froms.py
:
widgets = {
'birthdayMonth': MonthPickerInput(
options={
"format":"MMMM, YYYY",
}
),
}
这在前端正确显示,但是表单验证始终失败(每当我提交表单时,日历输入将突出显示为红色,但没有错误消息)。
在命中if form.is_valid()
和添加format
到打印的小部件之前,我在views.py中打印了POST数据2020-08-01
,而在添加"format":"MMMM, YYYY"
之后打印08-2020
。我猜这是造成问题的原因。
我该如何只更改前端显示,而将后端保留为原始格式,以使我的验证不再奇怪?我想我需要使用JQuery,但是所有尝试都失败了:
// this does nothing
$('#birthdayMonth').datepicker({
format: 'MMMM/YYYY',
});
// I have tried many more things with JQuery but they do nothing or cause my code to go buggy (such as displaying two calendars on top of each other
我想做的另一件事是从POST数据中获取BirthdayMonth并添加day字段,然后再将其传递给我的clean方法。虽然我敢肯定这是行得通的,但它确实非常骇人,而且肯定会有更好的方法。
-编辑-如果我添加
birthdayMonth = forms.DateField(
input_formats=['MMMM, YYYY'],
widget=MonthPickerInput(format='MMMM, YYYY')
)
正如Ben所建议的那样,它传递December, 2020
了我的观点,这就是验证失败的原因。
谢谢。
“为了使用任意格式,必须为字段的input_formats和小部件的格式指定模式。”
class BirthdayForm(forms.Form):
birthdayMonth = forms.DateField(
input_formats=['MMMM, YYYY'],
widget=MonthPickerInput(format='MMMM, YYYY')
)
否则,以干净的方法添加“ day”字段不会有任何危害:
https://docs.djangoproject.com/zh-CN/3.0/ref/forms/validation/#cleaning-a-specific-field-attribute
class BirthdayForm(forms.Form):
# ...
def clean_birthdayMonth(self):
date_ = self.cleaned_data['birthdayMonth']
date_ = date_.replace(day=1)
return date_
如果您可以从表单中获取“ 08-2020”或“ 2020年8月”,则可以使用clean方法轻松地将其转换为python日期时间
class BirthdayForm(forms.Form):
# ...
def clean_birthdayMonth(self):
import datetime
dt_str = '08-2020'
dt_obj = datetime.datetime.strptime(dt_str, '%m-%Y')
dt_str = "August, 2020"
dt_obj = datetime.datetime.strptime(dt_str, '%B, %Y')
dt_str = self.cleaned_data['birthdayMonth']
dt_obj = datetime.datetime.strptime(dt_str, '%B, %Y')
return dt_obj
听起来确实要完成的方法是在form.is_valid()
运行之前捕获数据。https://docs.djangoproject.com/zh-CN/dev/ref/request-response/#querydict-objects
post = request.POST.copy() # To get a mutable version
dt_str = post['birthdayMonth'] # "August, 2020"
dt_obj = datetime.datetime.strptime(dt_str, '%B, %Y')
post['birthdayMonth'] = dt_obj
# don't forget to update original POST
request.POST = post
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句