Skip to content

Commit

Permalink
date picker
Browse files Browse the repository at this point in the history
  • Loading branch information
ericoc committed Jan 4, 2025
1 parent 3c273eb commit dfc0e42
Show file tree
Hide file tree
Showing 10 changed files with 118 additions and 13 deletions.
23 changes: 22 additions & 1 deletion apps/core/api/viewsets.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from datetime import date
from dateutil.relativedelta import relativedelta

from django.utils.decorators import method_decorator
from django.utils.timezone import localtime
from django.utils.timezone import localdate, localtime
from django.views.decorators.cache import cache_page

from rest_framework.exceptions import ParseError
Expand All @@ -22,6 +23,26 @@ def dispatch(self, request, *args, **kwargs):
def get_queryset(self):
qs = super().get_queryset()

start_date = None
start_search = self.request.query_params.get("start")
if start_search:
try:
start_date = date.fromisoformat(start_search)
except ValueError:
pass

end_date = None
end_search = self.request.query_params.get("end")
if end_search:
try:
end_date = date.fromisoformat(end_search)
except ValueError:
pass

if start_date and end_date:
return qs.filter(pk__range=[start_date, end_date])


if self.filterable:
for filterable in self.filterable:
value = self.request.query_params.get(filterable)
Expand Down
33 changes: 33 additions & 0 deletions apps/core/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from django import forms
from django.utils.timezone import localtime


class SearchDateForm(forms.Form):
"""Form to search for data, between start and end dates."""
start = forms.DateField(
required=False,
widget=forms.DateInput(
attrs={
'class': 'form-control-sm',
'label': 'start',
'name': 'start',
'type': 'date'
}
)
)
end = forms.DateField(
required=False,
widget=forms.DateInput(
attrs={
'class': 'form-control-sm',
'label': 'end',
'name': 'end',
'type': 'date'
}
)
)

def get_initial_for_field(self, field, field_name):
# Set date inputs "max" attribute to current time.
field.widget.attrs["max"] = localtime().strftime("%Y-%m-%d")
return super().get_initial_for_field(field, field_name)
11 changes: 9 additions & 2 deletions apps/core/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@
</style>
</head>
<body class="container-fluid">
<header class="mb-3">
<header>
<nav class="navbar navbar-dark navbar-expand">
<ul class="navbar-nav gap-3">
<ul class="navbar-nav gap-3 mx-3">
<li class="nav-item{% if title and title == 'Utilities' %} border border-primary rounded{% endif %}" title="Utilities (Home)">
<a class="btn btn-lg nav-link icon-link icon-link-hover{% if title and title == 'Utilities' %} active" aria-current="page{% endif %}" href="{% url 'home' %}" data-bs-toggle="tooltip" data-bs-title="Utilities (Home)" data-bs-placement="bottom">
<svg class="bi text-primary" aria-hidden="true">
Expand Down Expand Up @@ -86,6 +86,13 @@
</a>
</li>
</ul>
<!-- start: "{{ start }}" -->
<!-- end: "{{ end }}" -->
<form class="d-flex gap-2" method="post" role="search">
{% csrf_token %}
{{ form.as_div }}
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</nav>
</header>
<main class="container-fluid">
Expand Down
2 changes: 1 addition & 1 deletion apps/core/templates/utility.html
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
const chartLoading = document.getElementById('chart-loading')
const utilityTitle = '{{ title }}'
const xhr = new XMLHttpRequest()
xhr.open("GET", `/api/${utilityTitle.replace(" ", "_").toLowerCase()}/?format=json`)
xhr.open("GET", `/api/${utilityTitle.replace(" ", "_").toLowerCase()}/?format=json&start={{ start }}&end={{ end }}`)
xhr.onreadystatechange = async () => {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
const utilityUsageData = JSON.parse(xhr.responseText)
Expand Down
4 changes: 3 additions & 1 deletion apps/core/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,6 @@
from .views.home import HomeView


urlpatterns = [path("", HomeView.as_view(), name="home")]
urlpatterns = [
path("", HomeView.as_view(), name="home")
]
53 changes: 49 additions & 4 deletions apps/core/views/base.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,62 @@
from datetime import timedelta

from django.conf import settings
from django.views.generic.base import TemplateView
from django.utils.timezone import localdate
from django.views.generic.edit import FormView

from ..forms import SearchDateForm


class BaseView(TemplateView):
class BaseView(FormView):
"""Base view."""
http_method_names = ("get",)
# icon = None
dates = initial = {}
default_start = {}
form_class = SearchDateForm
http_method_names = ("get", "post")
template_name = "utility.html"
title = None

def setup(self, request, *args, **kwargs):
# Set default search start and end datetime values.

today = localdate()
self.dates["start"] = None
if self.default_start:
self.dates["start"] = today - timedelta(**self.default_start)
self.dates["end"] = today

return super().setup(request, *args, **kwargs)


def form_valid(self, form):
# When valid, use the submitted form search dates.
for when in "start", "end":
if form.cleaned_data[when]:
self.dates[when] = form.cleaned_data[when]

return self.render_to_response(self.get_context_data(form=form))

def get_context_data(self, **kwargs):
# Include start and end dates in context.
context = super().get_context_data(**kwargs)

for when in "start", "end":
if self.dates[when]:
context[when] = self.dates[when].strftime("%Y-%m-%d")

context["timezone"] = settings.TIME_ZONE
context["title"] = self.title.replace("_", " ").title()
context["website_title"] = settings.WEBSITE_TITLE

return context

def get_initial(self):
# Set initial form search date values.
initial = super().get_initial()
for when in "start", "end":
if self.dates[when]:
initial[when] = self.dates[when].strftime("%Y-%m-%d")
return initial

def get_success_url(self):
return self.request.path
1 change: 0 additions & 1 deletion apps/core/views/utility.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,5 @@ def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["color"] = self.color
context["datatable_time_format"] = self.datatable_time_format
# context["icon"] = self.icon
context["thresholds"] = self.thresholds
return context
2 changes: 1 addition & 1 deletion apps/electric/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ class ElectricView(UtilityView):
"""Electric usage view."""
color = "e4a11b"
datatable_time_format = "datetime('DDDD, tt')"
# icon = "lightbulb"
default_start = {"days": 366.5}
thresholds = (1, 0.75, 0.5)
1 change: 0 additions & 1 deletion apps/natural_gas/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,4 @@ class NaturalGasView(UtilityView):
"""Natural gas usage view."""
color = "853cfd"
datatable_time_format = "datetime('MMMM y')"
# icon = "fan"
thresholds = (50, 25, 10)
1 change: 0 additions & 1 deletion apps/water/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,4 @@ class WaterView(UtilityView):
"""Water usage view."""
color = "2caffe"
datatable_time_format = "date('DDDD')"
# icon = "droplet"
thresholds = (100, 75, 50)

0 comments on commit dfc0e42

Please sign in to comment.