The following is a micro tutorial, on how I sent dates from the front end using Luxon to my backend Django.
Dot Point Context
- User will record start and end date for their project in NearBeach
- The datetime picker used is vue-datetime for the datetime picker.
- Vue-datetime uses the new Luxon library
- The project I am talking about is this micro tutorial is NearBeach
Method
The vue-datetime widget wants the datetime input to be a simple string. So - lets convert
this.localEndDateModel = this.endDateModel.toISO();
this.localStartDateModel = this.startDateModel.toISO();
When the user hits the submit button, we use Axios to send the data through the POST method. First we have to compile the data we want to send
//Create data_to_send
const data_to_send = new FormData();
data_to_send.set('project_name',this.projectNameModel);
data_to_send.set('project_description',this.projectDescriptionModel);
data_to_send.set('organisation',this.stakeholderModel['value']);
data_to_send.set('project_start_date',this.projectStartDateModel);
data_to_send.set('project_end_date',this.projectEndDateModel);
// Insert a new row for each group list item
this.groupModel.forEach((row,index) => {
data_to_send.append(`group_list`,row['value']);
});
As you can see in the code - it does not matter that we are sending the string value. We will be modifying the Django Form to accept this string value.
In the Django form, we want to edit the input format for the datetime fields to accept the ISO_8061. This requires placing the attribute input_formats=['c'],
inside the DateTimeField.
class NewProjectForm(forms.ModelForm):
project_start_date = forms.DateTimeField(
input_formats=['c'],
)
project_end_date = forms.DateTimeField(
input_formats=['c'],
)
group_list = forms.ModelMultipleChoiceField(
required=True,
queryset=group.objects.filter(
is_deleted=False,
)
)
# Basic Meta Data
class Meta:
model = project
fields = [
'project_name',
'project_description',
'project_start_date',
'project_end_date',
'organisation',
]
The form will now accept your Luxon iso string.
Quick notes
The ISO 8061 standard was implemented in Django 3.1 as discussed in the release notes
Top comments (0)