Hanny
Hanny

Reputation: 2159

Filter by a specific date in Django (mm/dd/yyyy)

In Django I have a 1 input form that is created like this:

class ListTripsForm(forms.Form):
    date_to_edit = forms.DateField(input_formats=['%m/%d/%Y'],
                                   widget=forms.TextInput(attrs={
                                        'class': 'form-control',
                                        'id': 'trips_month'}),
                                   initial=date.strftime(date.today(),
                                                         '%m/%d/%Y'))

The user selects a date (eg. 5/26/2017).

In the DB I have a datetime column.

Trying to get all the 'trips' from that day.

I've tried a few different ways and none have lead to success.

I am trying to add a filter to select just results from that day:

date = request.POST.get('date_to_edit', '')  # users submitted date mm/dd/yyyy
user_trips_for_date = Trip.objects.filter(user_id=user.id, trip_date=datetime.date(date))

What's the best way to accomplish this?

Upvotes: 0

Views: 1639

Answers (1)

Peter DeGlopper
Peter DeGlopper

Reputation: 37319

First off, you'll have an easier time of things if you instantiate your form as normal and access the field rather than extracting it directly from request.POST. Part of the point of the form classes is to handle type conversions.

Once you have that, if trip_date is a DateTimeField:

form = ListTripsForm(request.POST)
user_trips_for_date = Trip.objects.filter(user_id=user.id, trip_date__date=form.cleaned_data['date_to_edit'])

Plus the usual validation code of course, the point is to a) use the form to get a datetime.date instance and then b) use a __date filter clause.

Upvotes: 1

Related Questions