【发布时间】:2016-03-31 22:12:52
【问题描述】:
我有一个带有日期/时间输入的表单,输入接口由 Bootstrap 3 datetimepicker 提供。当我尝试提交表单时,它给了我一个验证错误,因为时间由于 am/pm 组件而无效。如何更改模型接受为有效日期/时间的格式,以便正确解析 am/pm 组件?或者有没有办法在JS中预处理日期?
views.py
def new_appointment_existing_client(request):
form = NewAppointmentExistingClientForm()
context = {'form': form}
if request.method == 'POST':
form = NewAppointmentExistingClientForm(data=request.POST)
context['form'] = form
#form.data['date'] = datetime.datetime.strptime(form.data['date'], '%Y-%m-%d %H:%M %p')
if form.is_valid():
form.save()
return HttpResponseRedirect('/calendar/')
return render(request, 'new_appointment.html', context)
new_appointment.html
{% extends 'base.html' %}
{% block startscripts %}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.css" type="text/css" media="all" />
{% endblock startscripts %}
{% block content %}
<h3>Create an Appointment</h3>
<br>
<br>
<div class='row'>
<div class='col-md-6'>
<form method='POST' action ='/new_appointment/' id='id_new_appointment_form' enctype="multipart/form-data">
{{ form.as_p }}
{% csrf_token %}
{% if form.errors %}
<div class='form-group has-error'>
<span class='help-block'>{{ form.text.errors }}</span>
</div>
{% endif %}
<input type="submit" id='id_form_submit' value="Submit" />
</form>
</div>
</div>
{% endblock content %}
{% block endscripts %}
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js'></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/bootstrap.datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
<script>
jQuery(document).ready(function($){
jQuery("#id_date").datetimepicker({
format: 'YYYY-MM-DD hh:mm a'
});
});
</script>
{% endblock endscripts %}
models.py
class Appointment(models.Model):
date = models.DateTimeField()
appointment_person = models.ForeignKey(Person)
forms.py
class NewAppointmentExistingClientForm(forms.models.ModelForm):
class Meta:
model = Appointment
fields = ('date',
'appointment_person',
)
widgets = {
'date': forms.DateTimeInput(format=['%Y-%m-%d %I:%M %p']),
}
【问题讨论】:
标签: javascript python django forms twitter-bootstrap