Reputation: 119
I'm working on a todo web app and has a user enter an events datetime with a custom bootstrap datetimepicker from here. I have the custom widgets on a form formatted to MM/DD/YY hh:mm A. However, Django doesn't accept the form. A similar question has been asked, but instead of overriding the default DateTimeInput, I would like the form to display in a certain format but be stored in a database in the default format. I'm thinking of using widget tweaks to customize the picker but I don't know how to store it in default formats. What would be the best way to do this?
Forms.py
from bootstrap_modal_forms.forms import BSModalForm
from .widgets import BootstrapDateTimePickerInput
from bootstrap_datepicker_plus import DateTimePickerInput
from .models import ToDoItem
class NewEventForm(BSModalForm):
class Meta:
model = ToDoItem
fields = ['title', 'description', 'start_time', 'end_time', 'remind_time']
widgets = {
'start_time': DateTimePickerInput(
options={"format": "MM/DD/YYYY hh:mm A"}
),
'end_time': DateTimePickerInput(
options={"format": "MM/DD/YYYY hh:mm A"}
),
'remind_time': DateTimePickerInput(
options={"format": "MM/DD/YYYY hh:mm A"}
),
}
Event form:
{% load bootstrap4 %}
{% load static %}
{% bootstrap_css %}
{% bootstrap_javascript jquery='full' %}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- Custom Stylesheet -->
<link rel="stylesheet" type="text/css" href="{% static 'main/main.css' %}">
<!-- Moment.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js" integrity="sha256-VBLiveTKyUZMEzJd6z2mhfxIqz3ZATCuVMawPZGzIfA=" crossorigin="anonymous"></script>
{{ form.media }}
</head>
<body>
<form method="POST" action="">
{% csrf_token %}
<div class="modal-header">
<h5 class="modal-title">New Event</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<fieldset class="form-group">
{% bootstrap_form form %}
</fieldset>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="submit-btn btn btn-primary">Create</button>
</div>
</form>
</body>
</html>
Upvotes: 0
Views: 424
Reputation:
You can do it in the frontend using at least 3 well-known JS date/time manipulators and the native stack. And you can do it in the backend, using django's tools, the python datetime library, a library called dateparse, dateparser, python dateutil etc etc.
It's a commonly solved problem (for school papers for example) :)
But the one thing that's going to help you is to know that form fields have a method called to_python()
: you can subclass the DateTimeField and override the method.
You don't have to take care of the way back, but for completeness if you wanted to, it would be Widget.format_value()
.
The best format to use in the backend (or actually everywhere where humans don't have to look at it) is Iso8601.
Upvotes: 1