Issue
I am creating a filter in heatmap where the filter will only extract the date from and to date transaction only. I am not sure with the codes on the filter date but I have not received an error, It only goes top of the page. My HTML for date is MM/DD/YYYY. I am not sure if it helps. But how can I embed filter between dates? Thank you
Views
def index_map(request):
if request.method == "POST":
fromdate = request.POST.get('fromdate')
todate = request.POST.get('todate')
df = pd.DataFrame(IncidentGeneral.objects.filter(user_report__date__date__range=(fromdate, todate)).values('user_report__latitude', 'user_report__longitude', 'accident_factor'))
print(df)
# coordenadas = list(IncidentGeneral.objects.values_list('user_report__latitude','user_report__longitude'))[-1]
map1 = folium.Map(location=[14.676208, 121.043861],
zoom_start=12,
)
# df = df.dropna(axis=0, subset=['user_report__latitude', 'user_report__longitude', 'accident_factor', 'user_report__date'])
# mapquestopen
fg3=folium.FeatureGroup(name='Map with Markers', show=True)
map1.add_child(fg3)
# marker_cluster = MarkerCluster().add_to(fg)
folium.TileLayer(('openstreetmap'), attr='openstreetmap').add_to(map1)
# folium.TileLayer('mapquestopen', attr='mapquestopen').add_to(map1)
# folium.TileLayer('MapQuest Open Aerial', attr='MapQuest Open Aerial').add_to(map1)
folium.TileLayer('cartodbpositron', attr='cartodbpositron').add_to(map1)
folium.TileLayer('cartodbdark_matter', attr='cartodbdark_matter').add_to(map1)
plugins.Fullscreen(position='topright').add_to(map1)
folium.LayerControl().add_to(map1)
for id,row in df.iterrows():
folium.Marker(location=[row['user_report__latitude'],row['user_report__longitude']], icon=folium.Icon(icon="car", prefix='fa') ,popup=row['accident_factor']).add_to(fg3)
# folium.Marker(coordenadas).add_to(map1)
# df['user_report__date'] = df['user_report__date'].sort_values(ascending=True)
# data = []
# for _, d in df.groupby('user_report__date'):
# data.append([[row['user_report__latitude'], row['user_report__longitude'], row['accident_factor']] for _, row in d.iterrows()])
map1 = map1._repr_html_()
context = {
'map1': map1
}
return render(request, 'index1.html', context)
Views
class UserReport(models.Model):
PENDING = 1
APPROVED = 2
REJECTED = 3
STATUS = (
(PENDING, 'Pending'),
(APPROVED, 'Approved'),
(REJECTED, 'Rejected')
)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
description = models.TextField(max_length=250, blank=True)
address = models.CharField(max_length=250)
country = models.CharField(max_length=50, blank=True, null=True)
state = models.CharField(max_length=50, blank=True, null=True)
city = models.CharField(max_length=50, blank=True, null=True)
pin_code = models.CharField(max_length=6, blank=True, null=True)
latitude = models.FloatField(max_length=20, blank=True, null=True)
longitude = models.FloatField(max_length=20, blank=True, null=True)
upload_photovideo = models.FileField(upload_to='incident_report/image', blank=True, null=True)
date = models.DateField(auto_now_add=False, auto_now=False, blank=True, null=True)
time = models.TimeField(auto_now_add=False, auto_now=False, blank=True, null=True)
status = models.PositiveSmallIntegerField(choices=STATUS, blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def get_status(self):
if self.status == 1:
incident_status = 'Pending'
elif self.status == 2:
incident_status = 'Approved'
elif self.status == 3:
incident_status = 'Rejected'
return incident_status
def save(self, *args, **kwargs):
super(UserReport, self).save(*args, **kwargs)
if self.upload_photovideo:
if ".jpg" in self.upload_photovideo.url or ".png" in self.upload_photovideo.url:
#check if image exists before resize
img = Image.open(self.upload_photovideo.path)
if img.height > 1080 or img.width > 1920:
new_height = 720
new_width = int(new_height / img.height * img.width)
img = img.resize((new_width, new_height))
img.save(self.upload_photovideo.path)
HTML
<div class="row">
<!-- Heat Map-->
<div class="col-xl-12">
<div class="card shadow mb-4">
<!-- Card Header - Dropdown -->
<div
class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
<h6 class="m-0 font-weight-bold text-primary">Heat Map</h6>
</div>
<!-- Card Body -->
<div class="card-body">
<div>
<div class="container">
<div class="row mt-4">
<div class="col-md-10 offset-md-1">
<form method="post">
{% csrf_token %}
<div class="modal-header">
<h4 class="modal-title">Filter Reports</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
<i class="fa-solid fa-xmark"></i>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>From</label>
<input type="date" name="fromdate" class="form-control date" required>
</div>
<div class="form-group">
<label>Until</label>
<input type="date" name="todate" class="form-control date" required>
</div>
<label class="text-danger">Please ensure that the correct dates has been selected.</label>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
<input type="submit" class="save-myreports-btn" value="Save Changes">
</div>
</form>
{{ map1|safe }}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- End of Heat Map-->
</div>
Solution
I’m guessing what you mean is you want to filter your objects based on the to and from dates.
In that one way is to use the range lookup like you do but the issue is you’re using the field date from the user report instead of created_at
which you have in your UserReport
model.
def index_map(request):
if request.method == "POST":
fromdate = request.POST.get('fromdate')
todate = request.POST.get('todate')
df = pd.DataFrame(IncidentGeneral.objects.filter(user_report__created_at__date__range=(fromdate, todate)).values('user_report__latitude', 'user_report__longitude', 'accident_factor'))
print(df)
# coordenadas = list(IncidentGeneral.objects.values_list('user_report__latitude','user_report__longitude'))[-1]
map1 = folium.Map(location=[14.676208, 121.043861],
zoom_start=12,
)
# df = df.dropna(axis=0, subset=['user_report__latitude', 'user_report__longitude', 'accident_factor', 'user_report__date'])
# mapquestopen
fg3=folium.FeatureGroup(name='Map with Markers', show=True)
map1.add_child(fg3)
You can also do:
df = pd.DataFrame(IncidentGeneral.objects.filter(user_report__created_at__date__gte=fromdate, user_report__created_at__date__lte=todate).values('user_report__latitude', 'user_report__longitude', 'accident_factor'))
Answered By – kwamito
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0