Check if id exists in db

I am trying to check if nationalID exists in db if so redirect to specifict page other wise redirect to registration page.

I am using try and except the except redirects but try is not redirecting to the required page.

views.py

from django.core.exceptions import ObjectDoesNotExist
from .forms import nationalId, patientForm

def register(request):
    page_name = 'patients'

    form = nationalId()

    if request.method == "POST":
        form= nationalId(request.POST)
        if form.is_valid():
            try:
                Patient.objects.get(national_id = request.POST['national_id'])
                return HttpResponseRedirect (reverse ("patient:homePage"))
            except ObjectDoesNotExist:
                return HttpResponseRedirect (reverse ("patient:patientReg", args=[request.POST['national_id']]))

I see a departure from naming conventions (classes starting with lower case characters) and missing contexts (e.g. where did the Patient class come from?).

In any case:
Django usually provides ids to table entries (models), therefore national_id is confusing unless you intentionally bypassed Django’s defaults.

how about:
Patient.objects.get(pk=int(request.POST['national_id']))

I am assuming national_id expects an integer. I do not see any cleaning happening in your view, so you may be unintentionally passing a string value as primary key.

It may help to see the relevant potions of models.py

models.py

class Patient(models.Model):
    # Unique ID for each patient
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, max_length=36)
    # Patient's first name
    first_name = models.CharField(_("first name"), max_length=150)
    # Patient's last name
    last_name = models.CharField(_("last name"), max_length=150)
    # Patient's national ID
    national_id = models.BigIntegerField(_("الرقم القومي"), unique=True)
    # Patient's home street
    home_address = models.CharField(_("عنوان المنزل"), max_length=50)
    # Patient's phone number
    phone_number = PhoneNumberField(_("رقم المحمول"))
    # Patient's insurance
    insurance = models.ForeignKey(Insurance, on_delete=models.CASCADE)
    # Patient's job
    job = models.CharField(_("العمل"), max_length=50)
    # Patient's date of birth
    date_of_birth = models.DateField()
    # Patient's gender
    gender = models.CharField(_("الجنس"), choices=(('ذكر', 'ذكر'), ('أُنثي', 'أُنثي')), max_length=8)
    # Patient's social status
    social_status = models.CharField(_("الحالة الإجتماعية"), choices=(('أعزب', 'أعزب'),('مُتزوج', 'مُتزوج'), ('أرمل', 'أرمل'),('مُطلق', 'مُطلق')), max_length=10)
    # Date and time when the patient was created
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f'{self.first_name} {self.last_name}'

and what about nationalId in forms.py ?

Patient.objects.get(national_id = request.POST['national_id'])

what was your intention with the above line? What happens to the object? It is not assigned to any variable so it is lost

You’re saying what it’s not doing, but you’re not explaining what it is doing.

Are you getting any kind of error message in your runserver console? Is it just redirecting you to the homePage?

Note: You’re also not showing a complete view here. There are other conditions involved for which you’re not showing the code. (What happens on a GET instead of a POST? What happens if the form is invalid?)

this is something like a clinic webapplication, so the admin logs in with his credentials then enters patients national id if patient is registered he gets to choose the clinic and appointment if not he is redirected to patient registration form where he enters patient data then makes the appointment for him

class nationalId(forms.ModelForm):
    class Meta:
        model= Patient
        fields = ['national_id']

if patient is not registered the redirect works as expected and i can register new patients and then schedule appointment but my problem is with redirecting if patient already exists the page just refreshes when i click submit and nothing happens and i don’t get any errors in the terminal

Please post the full view.

views.py

def register(request):
    page_name = 'patients'

    form = nationalId()

    if request.method == "POST":
        form= nationalId(request.POST)
        if form.is_valid():
            try:
                patient = Patient.objects.get(national_id = int(request.POST['national_id']))
                if patient:
                    return HttpResponseRedirect (reverse ("patient:homePage"))
            except ObjectDoesNotExist:
                return HttpResponseRedirect (reverse ("patient:patientReg", args=[request.POST['national_id']]))
                
    today = date.today()
    
    context = {
        'page': page_name,
        'date': today,
        'form': form
        }
    return render(request, 'core/patients/registerPatient.html', context)

That behavior leads me to believe that the is_valid test on the form is returning false. (You’re not showing your template, but I’m going to guess that you’re not rendering any form errors in your template.)

You could add an else clause to the if form.is_valid() conditional and do something like print the form errors to the console, just to see whether this is the case.

Side note: Since you’re using a form for input, and you have a field for national_id, I suggest you use form.cleaned_data['national_id'] in your query instead of directly accessing request.POST. The cleaned_data dict has already performed basic validation and data conversion of the input field. (I don’t think this matters yet because I don’t believe you’re getting this far.)

As you expected it was throwing an error that the value already exists in the db so when i used else for the if form.is_valid() it worked.
Thanks a lot for your continuous help.

def register(request):
    page_name = 'patients'

    form = nationalId()

    if request.method == "POST":
        form= nationalId(request.POST)
        if form.is_valid():
            return HttpResponseRedirect (reverse ("patient:patientReg", args=[form.cleaned_data['national_id']]))
        else:
            print(form.errors)
            return HttpResponseRedirect (reverse ("patient:homePage"))
                
    today = date.today()
    
    context = {
        'page': page_name,
        'date': today,
        'form': form
        }
    return render(request, 'core/patients/registerPatient.html', context)

I remember when I had a similar issue with a web app I was working on. What finally helped me out was simplifying the logic and using a different approach. Have you considered incorporating an identity validation service into your project? They offer tools that could potentially streamline your database checks and make redirection smoother.

Have you considered incorporating an identity validation service like ID Analyzer into your project?