Home > Software engineering >  DateField as a search field. How to make if look like a calendar
DateField as a search field. How to make if look like a calendar

Time:02-01

class OveroptimisationIdentifiers(models.Model):
    date = models.DateField(blank=True, null=True)
    region = models.ForeignKey(SiteRegions, models.CASCADE)
    site = models.ForeignKey(SiteSites, models.CASCADE)

    def __str__(self):
        return "{}: {}: {}".format(self.date, self.region, self.site)

    class Meta:
        managed = False
        db_table = 'overoptimisation_identifiers'
        unique_together = (('date', 'site', 'region'),)



@admin.register(OveroptimisationIdentifiers)
class OveroptimisationIdentifiersAdmin(admin.ModelAdmin):
    exclude = []
    actions = [scrape_arsenkin, ]
    list_filter = ["date", ]
    search_fields = ["date", ]

It is strange to me but this code produces just an input field rather than a calendar picker.

enter image description here

Could you help me convert it into a calendar picker?

CodePudding user response:

I do not think you could do that from within your views. I guess you would need to override that part of the template. I am not 100% sure, but the field looks hardcoded inside the django template to me.

Read here, how to override a template.

Go to corresponding template at "django/contrib/admin/templates/admin/search_form.html"

Copy all content to clipboard.

Create folder structure like so:

  • create folder called templates/ inside your project. So at the same stage where all your app folders and your manage.py files are.
  • templates/admin/your_custom_app_name/
  • crate file with full filepath: your_project/templates/admin/your_custom_app_name/search_form.html

Then paste the content from your clipboard. Type some "hello world" world in there. Then check if your "hello world" now shows up somewhere inside the view you want to customize. If it shows up you have successfully overridden the template.

Sadly I am very bad with html. You have to work out the rest alone. But you need to replace this part:

<label for="searchbar"><img src="{% static "admin/img/search.svg" %}" alt="Search"></label>
<input type="text" size="40" name="{{ search_var }}" value="{{ cl.query }}" id="searchbar" autofocus{% if cl.search_help_text %} aria-describedby="searchbar_helptext"{% endif %}>
<input type="submit" value="{% translate 'Search' %}">

Try to still keep the variables, to ensure the functionality of your view is not messed up.

  • Related