0

I have a database, in which it's possible to find products by their name. The DB has ID, category, name, amount and date defined, and I was trying to create a separate search field that would let me search those items by the date they were added.

The models.py looks like this:

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

    category = models.ForeignKey(Category, models.PROTECT, null=True, blank=True)

    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}'

And views.py looks like this:

class ExpenseListView(ListView):
    model = Expense
    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)

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

I've added the "date" field under the "name", following it's structure, but I kept getting the 'datetime.date' object has no attribute 'strip' error. Is there a different format for defining the date? When I've also added it to the search field in forms.py, it was seen there as a string.

I've also found a similar post from How to make date range filter in Django?, but it didn't explained that much, even after searching in the official library. I'm very new to Django, and I'm not sure if there should be a separate queryset call out for searching by date too.

In form.is_valid() I've tried to add the date field, but I kept getting the 'datetime.date' object has no attribute 'strip' error.

MattFPy
  • 21
  • 4
  • I'm not sure its related to your question but I notice you might be misunderstanding the usage of the `db_index=True` kwarg of a model field. Please see: https://stackoverflow.com/questions/59596176/when-we-should-use-db-index-true-in-django – Swift Oct 25 '22 at 17:14

1 Answers1

0

I think the behaviour you're looking for is described I. The django documentation here:

https://docs.djangoproject.com/en/4.1/ref/models/fields/#django.db.models.DateField.auto_now

DateField

field_name = DateField(auto_now=False, auto_now_add=False, **options)

A date, represented in Python by a datetime.date instance. Has a few extra, optional arguments:

DateField.auto_now

Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it’s not just a default value that you can override.

The field is only automatically updated when calling Model.save(). The field isn’t updated when making updates to other fields in other ways such as QuerySet.update(), though you can specify a custom value for the field in an update like that.

DateField.auto_now_add

Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it’s not just a default value that you can override. So even if you set a value for this field when creating the object, it will be ignored. If you want to be able to modify this field, set the following instead of auto_now_add=True:

For DateField:

default=date.today - from datetime.date.today()

For DateTimeField:

default=timezone.now - from django.utils.timezone.now()

The default form widget for this field is a DateInput. The admin adds a JavaScript calendar, and a shortcut for “Today”. Includes an additional invalid_date error message key.

Swift
  • 1,663
  • 1
  • 10
  • 21