Home > Mobile >  How to get previous Date can anyone please? Actually I m working on Blood donation project
How to get previous Date can anyone please? Actually I m working on Blood donation project

Time:12-17

#Models.py
from django.db import models

class User(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    mobile_number = models.IntegerField()
    cnic = models.CharField(max_length = 13)
    blood_group = models.CharField(max_length= 10)
    last_donation = models.DateTimeField(auto_now_add=True)

#Views.py
from django.shortcuts import render
from .models import *
from .forms import UserForm
from datetime import  datetime,timedelta
from django.contrib import messages

def home(request):
    return render(request, 'home.html')

def donor(request):
    if request.method == "POST":
        userform = UserForm(request.POST)
        if userform.is_valid():
            userform.save()
    else:
        userform = UserForm()
    return render(request, 'donor.html',{'userform':userform})    
#forms.py
from django.core.exceptions import ValidationError
from django.forms import ModelForm
from .models import User
from datetime import  datetime,timedelta
from django.shortcuts import render

class UserForm(ModelForm):
    class Meta:
        model = User
        fields = "__all__"
    
    def clean_cnic(self):
        cnic = self.cleaned_data['cnic']
        print("This is a cnic",cnic)
        if User.objects.filter(cnic = cnic).exists():
            # i want to get previous date 
            

Actually I m working on Blood donation project. first time user will come he or she entered data and the date will automatically add Beacuse it is auto_now_add. Again the same user will come and entered data I will match the CNIC if user is exist if user exist then I have to get previous date and after getting previous date I have to minus previous date from current date to check it completed 90 days if not then I have to show message "U have to wait 90 days to complete" How I get previous date?

CodePudding user response:

You probably want something like this:- (I think if cnic is a unique field you should set a unique or primary key constraint on it)

existing_user = User.objects.get(cnic=cnic)

if existing_user:
  previous_date = existing_user.last_donation 
  current_date = datetime.datetime.now()
  days_diff = (current_date - previous_date).days

CodePudding user response:

You can get the instance inside your clean method with self.instance.

def clean_cnic(self):
    cnic = self.cleaned_data['cnic']
    print("This is a cnic",cnic)
    if User.objects.filter(cnic = cnic).exists():
        # i want to get previous date 
        if self.instance:
           prev_date = self.last_donation.date()
           # your logic now
  • Related