Compare Date from a database to current date and alert user if it's late

Viewed 104

I have a database set up, I am running Django for the backend and React.js for the front. This is a project for school but I am having a hard time finding information on how to do this properly.

I want to take the date put for the inspection_date and compare that to the local time, and if local time is greater than inspection_date, alert the user that they are past the inspection date.

Here is my class model

class Hive(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    hive_number = models.IntegerField()
    inspection_date = models.DateField()

My Serializer

class HiveSerializer(serializers.ModelSerializer):
    class Meta:
        model = Hive
        fields = ['id', 'hive_number', 'inspection_date', 'user_id']
        depth = 1

1 Answers

You can make use of @property decorator for doing these things and set custom logic of checking whether user's inspection date passed the today's date or not.

If user's inspection date has passed the today's date then show something like you are not eligible for inspection, vice-versa.

models.py

from django.db import models
from django.contrib.auth.models import User
from datetime import date


class Hive(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    hive_number = models.IntegerField()
    inspection_date = models.DateField()

    @property
    def eligiblity_for_inspection(self):
        current_date = date.today()
        if current_date < self.inspection_date:
            return True
        else:
            return False

    def __str__(self):
        f"Hive number **{self.hive_number}**"

urls.py

from django.urls import path
from . import views
urlpatterns = [
    path('', views.home, name='home')
]

views.py

from django.shortcuts import render
from .models import Hive


def home(request):
    all_hives = Hive.objects.all()
    context = {
        'all_hives': all_hives
    }
    return render(request, 'home/index.html', context)

template file or index.html

<body>
    {% for hive in all_hives  %}
        <div class="info">
            <p>{{forloop.counter}} record</p>
            <p>{{hive.user.username}}</p>
            <p>{{hive.inspection_date}}</p>
            {% if hive.eligiblity_for_inspection %}
                <p>you are eligible for inspection</p>
            {% else %}
                <p>You are not eligible for inspection</p>
            {% endif %}
        </div>
        <hr>
    {% endfor %}
</body>

It will give desired output, if today's date is greater than inspection date, then you can show any custom message, also in alert.

Related