33 – HOW TO DO A DATE RANGE FILTER IN DJANGO – STOCK MANAGEMENT SYSTEM

Spread the love

33 – HOW TO DO A DATE RANGE FILTER IN DJANGO – STOCK MANAGEMENT SYSTEM

Searching object in django can be archieved in multiple ways. In this video we will try to search objects within a certain date range.

For example, we have an object that was issued out on different dates. Let’s say one was

1 July 2020, 2nd July 2020, 5th July 2020, and 20th July 2020.

Now we want to filter all the issued items from 1st July 2020 up to today 28th July 2020.

This type of filter is what we want to archieve in this tutorial.

Feel free to leave a comment if you have any issue or needed some clarification while implimenting this cool little feature.

Step 1. Make a form in forms.py

Import StockHistory Model then create a form with the fields needed to do a search. In this case, we will update the form we already used our previous blogs of this series, and include two extra fields: start_date and end_date.

class StockHistorySearchForm(forms.ModelForm):
	export_to_CSV = forms.BooleanField(required=False)
	start_date = forms.DateTimeField(required=False)
	end_date = forms.DateTimeField(required=False)
	class Meta:
		model = StockHistory
		fields = ['category', 'item_name', 'start_date', 'end_date']

Step 2. Create the filter in views.py

Now that we have a form with the a start and end date field, we can use this fields to do a range filter in the StockHistory Model.

In views.py, import and use the form created above in list_history view and then add a filter criterion that looks for the date within the start and end date in the form above.

queryset = StockHistory.objects.filter(
	item_name__icontains=form['item_name'].value(),
	last_updated__range=[
							form['start_date'].value(),
							form['end_date'].value()
						]
	)

NOTE: With this example (using date range), when selecting the start and end date, the end date should be one day beyond the last date you want to to display in the output. For example, if you want to select a date from

1st July 2020 to 28th July 2020,

Set your start date as 1st July 2020 and set the end date to 29th July 2020


Spread the love

About the author

arbadjie

Hi, I'm Abdourahman Badjie, an aspiring developer with obsession for anything coding and networking. This blog is dedicated to helping people learn to develop web applications using django framework.

View all posts

22 Comments

    • I’ve not covered that in the video. You will need to add another field in the StockHistory table to hold the ID of the data from the stock table. You can name that field stockID.
      Then modify the trigger to store the ID of the stock objects to the stockID field.
      Leave the default ID field of the StockHistory table to be auto-increment. This will allow the table to have a unique field. You can then delete the records as any table in Django. I might do a video on it but try it in the mean time.

      • Thanks man, you have made this coding thing a lot easier for me, i will try in the meanwhile… You dont know how im always waiting for the next release…you are the best tutor there is.

          • Hey Kennedy and Samuel. Thanks for the interest you showed on the tutorials. Am currently writing my post graduate dissertation. I am also engaged in some projects for clients. These are what take most of my time. I will try and post more when I have a bit more time because more and more people are liking it.
            You are surely true fans. Thanks buddies 🙂

  • Please I have a little problem here. I have been unable to publish anything on the website. It is saying “domain_name/admin/music/music/add/ not found on this server”. What’s wrong? I’ve tried contacting the hosting providers and they said the problem will from my end. Can you help? Please

      • Everything works fine on the local server, I don’t know what’s wrong with the deployment server. I changed the default database though, from sqlite3 to MySQL. Will that affect?

  • hi sir! i have a question about the date range filter you apply in stock management system. I have a problem when the forms of start date and end date is null ValidationError value has an invalid date format appear. How can i solve this problem

    • I believe I already covered this. Check around the videos I upload. Unfortunately, I do not have much time to answer every question. You should find the solution in one of my videos

    • if request.method == ‘POST’:
      category = form[‘category’].value()
      queryset = StockHistory.objects.filter(
      item__icontains=form[‘item’].value(),
      )

      if start_date == None or end_date == None:
      StockHistory.objects.filter(last_updated__range=[
      form[‘start_date’].value(),
      form[‘end_date’].value()
      ]
      )

  • If you are getting the error: [“” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.”]

    Change your views.py to this instead:
    if request.method == ‘POST’:
    category = form[‘category’].value()
    queryset = StockHistory.objects.filter(
    item__icontains=form[‘item’].value(),
    )

    if start_date == None or end_date == None:
    StockHistory.objects.filter(last_updated__range=[
    form[‘start_date’].value(),
    form[‘end_date’].value()
    ]
    )

Leave a Reply

Your email address will not be published. Required fields are marked *