0

I'd like to let a user search data by picking a date range.

MY MODEL

class Expense(models.Model):
    class Meta:
        ordering = ('date', '-pk')

    category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE)
    name = models.CharField(max_length=50)
    amount = models.DecimalField(max_digits=8, decimal_places=2)
    date = models.DateField(default=datetime.date.today, db_index=True)

    def __str__(self):
        return f'{self.date} {self.name} {self.amount}'

VIEWS.PY

class ExpenseListView(ListView):
    model = Expense  # imported db model
    paginate_by = 5

    def get_context_data(self, *, object_list=None, **kwargs):

        queryset = object_list if object_list is not None else self.object_list

        form = ExpenseSearchForm(self.request.GET)
        if form.is_valid():

            name = form.cleaned_data.get('name', '').strip()
            if name:
                queryset = queryset.filter(name__icontains=name)

            category = form.cleaned_data['category']
            if category:
                queryset = queryset.filter(category=category)

            grouping = form.cleaned_data['grouping']
            if grouping:
                queryset = queryset.order_by('date', '-pk')

        return super().get_context_data(
            form=form,
            object_list=queryset,
            summary_per_category=summary_per_category(queryset),
            summary_per_year_month=summary_per_year_month(queryset),
            total_amount_spent=total_amount_spent(),
            **kwargs)

I wish I could make this look & work like that (example from my app, 2 lines of html just to show you what result I want). I don't have a clue how to make it work with everything else, especially I want to include this to my ListView which already have one django form in it. Any thoughts? Maybe you could direct me somehow? Im absolutely confused after researching for whole day without any good result.

Ben
  • 2,348
  • 1
  • 20
  • 23
  • Can you not add the fields to the existing form? The django-filter package can be useful for creating forms that filter querysets https://django-filter.readthedocs.io/en/stable/ – Iain Shelvington Sep 03 '20 at 21:52
  • Im sorry but can you explain more? I am a newbie to django so you know :) –  Sep 03 '20 at 21:58

1 Answers1

0

You can use the following:

Expense.objects.all(date__range[START_DATE, END_DATE])

Update:

  1. To return a range from a Date field you can use the above example.

  2. get_context_data is used to pass additional information. If you wish to handle the data from the form use: post(self, request, *args, **kwargs). However, in this instance you only need the following:

     def get_context_data(self, *, **kwargs):
         context = super().get_context_data(**kwargs)
         context['form'] = YOUR_FORM_HERE
         return context
    

I'm unsure how you're handling forms and your view itself but (initially) you can set a variable called context_object_name (e.g. context_object_name = "results"; this will appear in view as {{{results}}).

Post() requires a HTTP response so you can use the render method:

args = {
   "results": Expense.objects.all(date__range[START_DATE, END_DATE])
}

return render(request, TEMPLATE_NAME, args)

Hope this helps!

rsigs
  • 48
  • 7