Home > Net >  User matching query does not exist. I want to add data if user is first time coming?
User matching query does not exist. I want to add data if user is first time coming?

Time:12-20

Actually I m working on Blood Donation system. I m checking that if user is already exist then I checking that He or She completed 90 days Or not if He or She completed then His or Her request will be accepted. if didn't complete then I will show message U have to Complete 90 days. I add data through data admin side and checked on the base of the CNIC that he or she completed 90 days completed or not and its Working But Now the main problem is that If add New Data from Front End he said User matching query does not exist. Now I have to Add else part But I don't know How? please tell me about that I m stuck from past 4 days.

 #forms.py 
    
    from django.core.exceptions import ValidationError
    from django.forms import ModelForm
    from django.shortcuts import redirect
    from .models import User
    from datetime import  datetime,timedelta
    
    
    class UserForm(ModelForm):
        class Meta:
            model = User
            fields = "__all__"
        
        def clean_cnic(self):
            cnic = self.cleaned_data['cnic']
            print("This is a cnic",cnic)
            existuser = User.objects.get(cnic = cnic)
            if existuser:
                previous_date = existuser.last_donation
                current_date = datetime.now().astimezone()
                print(previous_date,"-----_---",current_date)
                final = current_date - previous_date
                print("The final is -> ",final)
                if final < timedelta(days= 90):
                    raise ValidationError("U have to wait 90 days to complete")
                return final



 #views.py
    
    from django.shortcuts import render
    from .models import *
    from .forms import UserForm
    
    
    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})

CodePudding user response:

Simply, you need to make sure the user has exists.

def clean_cnic(self):
    cnic = self.cleaned_data['cnic']
    try:
        existuser = User.objects.get(cnic=cnic)
    except User.DoesNotExist:  
        raise ValidationError("User not found!")

    previous_date = existuser.last_donation
    current_date = datetime.now().astimezone()
    final = current_date - previous_date
    if final < timedelta(days= 90):
        raise ValidationError("U have to wait 90 days to complete")
    return final
  • Related