Home > Software engineering >  Django form is not submitted to the database
Django form is not submitted to the database

Time:10-07

I am writing a Django website for dentists, the dentist can register patients with form easily not an issue, however when registering visits for a patient it is not saved, in the admin panel both models works just fine, on the website the visits form dose not save to database.


models.py

from django.db import models

class Paitent(models.Model):

pname = models.CharField(max_length=50)
age = models.IntegerField()
gender = models.CharField(max_length=50)
address = models.CharField(max_length=50)
telephone = models.IntegerField()
mHistory = models.CharField(max_length=500, blank=True, null=True)   


def __str__(self):
    return self.pname

class Visit(models.Model):
paitent = models.ForeignKey(Paitent,null=True ,on_delete=models.CASCADE, blank=True)
toothNumber = models.CharField('involved tooth', max_length=120)
cComplaint = models.CharField('chief complaint',max_length=120)
sASymptoms = models.CharField('signs and symptoms',max_length=120)
diagnosis = models.CharField(max_length=120)
procedure = models.CharField(max_length=120)
notes = models.TextField(blank=True)
currentVisit = models.DateTimeField(
    'time and date of current visit', null=True)
nextAppointment = models.DateTimeField()

def __str__(self):
    return self.toothNumber

forms.py

 from django import forms
 from .models import Paitent
 from .models import Visit


 class PaitentForm(forms.ModelForm):
    class Meta:
         model = Paitent
         fields = ['pname', 'age', 'gender', 'address', 'telephone']
    
 class VisitForm(forms.ModelForm):
    class Meta:
         model = Visit
         fields = ['paitent', 'toothNumber', 'cComplaint',
              'sASymptoms', 'diagnosis', 'procedure',
              'notes', 'currentVisit', 'nextAppointment']

views.py

from django.shortcuts import render
from .models import Paitent
from .models import Visit
from .forms import PaitentForm
from .forms import VisitForm
import calendar
from calendar import HTMLCalendar


def homePage(request):
    all_paitents = Paitent.objects.all
    return render (request, 'homePage.html',{'all':all_paitents})

def newpaitent(request):
    if request.method == 'POST':
        form = PaitentForm(request.POST or None)
        if form.is_valid():
           form.save()
    return render(request, 'newpaitent.html', {})
        
else:
    return render(request, 'newpaitent.html', {})


def addVisit(request):
    if request.method == 'POST':
        form = VisitForm(request.POST or None)
        if form.is_valid():
           form.save()
        return render(request, 'addVisit.html', {})

else:
    return render(request, 'addVisit.html', {})

template

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
        {% load static %}
    <link rel="stylesheet" href="{% static 'css/bootstrap.min.css'  %}">
    <link rel="stylesheet" href="../static/css/addVisit.css">
    <link href="//db.onlinewebfonts.com/c/e662339992c4abf5b43f537391bd3169? 
     family=Candara" rel="stylesheet"
    type="text/css" />
    <title>Add Visit</title>
</head>
<body>

<!-- Title navbar -->

<div >

    <h1> Clinic Name </h1>
    <h2> Dental Clinic. </h2>

</div>

<!-- Drop down menu -->

    <div >
        <p id="add_appointment"> <a href="/"> Home </a></p>
        <hr id="hr_line">
        <p id="calender"> <a href="/calendar"> Calender </a></p>

</div>

<!-- Form -->

    <h4 > Add Current Visit : </h4>

    <form  method="POST" action="{% url 'addVisit' 
      %}">
     {% csrf_token %}
     {{form.as_p}}

    <div >
        <input   name="paitent">
    </div>

    <label> Involved Tooth :</label>
    <div >
        <div >
            <option onclick="toothNumber('UR8')">8</option>
            <option onclick="toothNumber('UR7')">7</option>
            <option onclick="toothNumber('UR6')">6</option>
            <option onclick="toothNumber('UR5')">5</option>
            <option onclick="toothNumber('UR4')">4</option>
            <option onclick="toothNumber('UR3')">3</option>
            <option onclick="toothNumber('UR2')">2</option>
            <option onclick="toothNumber('UR1')">1</option>
        </div>

        <div >
            <option onclick="toothNumber('UL1')">1</option>
            <option onclick="toothNumber('UL2')">2</option>
            <option onclick="toothNumber('UL3')">3</option>
            <option onclick="toothNumber('UL4')">4</option>
            <option onclick="toothNumber('UL5')">5</option>
            <option onclick="toothNumber('UL6')">6</option>
            <option onclick="toothNumber('UL7')">7</option>
            <option onclick="toothNumber('UL8')">8</option>
        </div>
    </div>

    <div > </div>
    <div > </div>

    <div >
        <div >
            <option onclick="toothNumber('LR8')">8</option>
            <option onclick="toothNumber('LR7')">7</option>
            <option onclick="toothNumber('LR6')">6</option>
            <option onclick="toothNumber('LR5')">5</option>
            <option onclick="toothNumber('LR4')">4</option>
            <option onclick="toothNumber('LR3')">3</option>
            <option onclick="toothNumber('LR2')">2</option>
            <option onclick="toothNumber('LR1')">1</option>
        </div>

        <div >
            <option onclick="toothNumber('LL1')">1</option>
            <option onclick="toothNumber('LL2')">2</option>
            <option onclick="toothNumber('LL3')">3</option>
            <option onclick="toothNumber('LL4')">4</option>
            <option onclick="toothNumber('LL5')">5</option>
            <option onclick="toothNumber('LL6')">6</option>
            <option onclick="toothNumber('LL7')">7</option>
            <option onclick="toothNumber('LL8')">8</option>
        </div>

        <div >
            <input type="text"  id="toothNumber" name="toothNumber" placeholder="Tooth Number">
        </div>

    </div>

    <div >

        <div >
        <input type="text"  id="ccomplain" name="cComplaint" placeholder="Chief Complaint">
        </div>
    
        <div >
        <input type="dropdown"  id="sasymptoms" name="sASymptoms" placeholder="Signs and Symptoms">
        </div>
    
        <div >
    
        <input  list="diagnosis" name="diagnosis" placeholder="Diagnosis" />

        <datalist id="diagnosis">
            <option value="Bad Oral Hygien"></option>
            <option value="Gingivitis"></option>
            <option value="Periodentits"></option>
            <option value="dental Stain"></option>
            <option value="dental and Gingival Stain"></option>
            <option value="Mobility"></option>
            <option value="Superficial Caires"></option>
            <option value="Deep Caires"></option>
            <option value="Reversible Pulpitis"></option>
            <option value="Irreversible Pulpitis"></option>
            <option value="Necrotic"></option>
            <option value="Retained Root"></option>
        </datalist>
        </div>

        <div >
            
        <input  list="procedure" name="procedure" placeholder="Procedure" required />
            
            <datalist id="procedure">
                <option value="Treatment"></option>
                <option value="Scalling and Polishing"></option>
                <option value="Deep Scalling and polishing"></option>
                <option value="Whitening"></option>
                <option value="Direct Pulp Capping"></option>
                <option value="Indirect Pulp Capping"></option>
                <option value="Amlgam Filling"></option>
                <option value="Composite Filling"></option>
                <option value="Build Up"></option>
                <option value="RCT"></option>
                <option value="Crown Preparation"></option>
                <option value="Extraction"></option>
            </datalist>
        </div>

        <div >
        
            <input  name="notes" placeholder="Notes"/>
        </div>
    </div>

    <label > Current Visit Date :</label>
    <div >
        <input type="datetime-local"  id="current_visit" name="currentVisit" required>
    </div>

    <label > Next Appointment :</label>
    <div >
            <input type="datetime-local"  
     id="appointment" 
    name="nextAppointment">
        </div>
     
        <div >
            <a href="javascript:history.back() " > 
    cancel </a>
            <button type="submit" > 
    Submit </button>
        </div>

    </form>


    <script>
    

    function toothNumber(string) {
    document.getElementById("toothNumber").value = string;
            }
    </script>


    
    </body>
    </html>

urls:

from django.urls import path
from . import views


urlpatterns = [
    path('', views.homePage, name='homePage'),
    path('newpaitent', views.newpaitent, name='newpaitent'),
    path('calendar', views.calendar, name='calendar'),
    path('paitentInfo', views.paitentInfo, name='paitentInfo'),
    path('addVisit', views.addVisit, name='addVisit'),
    path('paitentInfoSearched', views.paitentInfoSearched,
         name='paitentInfoSearched'),
    path('visits', views.visits, name='visits')

thank you in advance

CodePudding user response:

If the form is not valid, it wont be committed to database.

Print the form errors, this should help you understand why the form is not getting saved

if form.is_valid():
          form.save()
else:
          print(form.errors)

CodePudding user response:

I think you didn't provide context in view:

Instead of this:

def addVisit(request):
    if request.method == 'POST':
        form = VisitForm(request.POST or None)
        if form.is_valid():
           form.save()
        return render(request, 'addVisit.html', {})

    else:
         return render(request, 'addVisit.html', {})

try this:

     def addvisit(request):
        if request.method == 'POST':
            form = VisitForm(request.POST)
            if form.is_valid():
               try:
                   form.save()
                   return redirect("/") #Add your project route here where you want to go after adding visitors
               except:
                    pass
        else:
             form = VisitForm()  
        return render(request, 'addvisit.html', {'form':form})
            
  • Related