model.py
class Doctor(models.Model):
user=models.OneToOneField(User,on_delete=models.CASCADE)
address = models.CharField(max_length=40,null=True,blank=True, default=None)
mobile = models.CharField(max_length=20,null=True,blank=True,default=None)
department= models.CharField(max_length=50,choices=departments,default='Orthopedic')
status=models.BooleanField(default=True)
@property
def get_name(self):
return self.user.first_name+" "+self.user.last_name
@property
def get_id(self):
return self.user.id
def __str__(self):
return "{} ({})".format(self.user.first_name,self.department)
class Patient(models.Model):
user=models.OneToOneField(User,on_delete=models.CASCADE)
address = models.CharField(max_length=40,null=True,blank=True,default=None)
mobile = models.CharField(max_length=20,null=True,blank=True,default=None)
assignedDoctorId = models.ForeignKey(Doctor, on_delete=models.CASCADE)
admitDate=models.DateField(auto_now=True)
status=models.BooleanField(default=False)
@property
def get_name(self):
return self.user.first_name+" "+self.user.last_name
@property
def get_id(self):
return self.user.id
def __str__(self):
return self.user.first_name
forms.py
class DoctorUserForm(forms.ModelForm):
class Meta:
model=User
fields=['first_name','last_name','username','password']
widgets = {
'password': forms.PasswordInput()
}
class DoctorForm(forms.ModelForm):
class Meta:
model=models.Doctor
fields=['address','mobile','department','status']
class PatientUserForm(forms.ModelForm):
class Meta:
model=User
fields=['first_name','last_name','username','password']
widgets = {
'password': forms.PasswordInput()
}
class PatientForm(forms.ModelForm):
assignedDoctorId=forms.ModelChoiceField(queryset=models.Doctor.objects.all().filter(status=True),empty_label="Name and Department", to_field_name="id")
class Meta:
model=models.Patient
fields=['address','mobile','assignedDoctorId','status']
view.py
def doctor_signup_view(request):
userForm=forms.DoctorUserForm()
doctorForm=forms.DoctorForm()
mydict={'userForm':userForm,'doctorForm':doctorForm}
if request.method=='POST':
userForm=forms.DoctorUserForm(request.POST,prefix=userForm)
doctorForm=forms.DoctorForm(request.POST,request.FILES,prefix=doctorForm)
if userForm.is_valid() and doctorForm.is_valid():
user=userForm.save()
user.set_password(user.password)
user.save()
doctor=doctorForm.save(commit=False)
doctor.user=user
doctor=doctor.save()
my_doctor_group = Group.objects.get_or_create(name='DOCTOR')
my_doctor_group[0].user_set.add(user)
return HttpResponseRedirect('doctorlogin')
return render(request,'hospital/doctorsignup.html',context=mydict)
def patient_signup_view(request):
userForm=forms.PatientUserForm()
patientForm=forms.PatientForm()
mydict={'userForm':userForm,'patientForm':patientForm}
if request.method=='POST':
userForm=forms.PatientUserForm(request.POST,prefix=userForm)
patientForm=forms.PatientForm(request.POST,request.FILES,prefix=patientForm)
if userForm.is_valid() and patientForm.is_valid():
user=userForm.save()
user.set_password(user.password)
user.save()
patient=patientForm.save(commit=False)
patient.user=user
patient=patient.save()
my_patient_group = Group.objects.get_or_create(name='PATIENT')
my_patient_group[0].user_set.add(user)
logger.debug("This is a debug message")
else:
logger.debug("This is a debug message")
return HttpResponseRedirect('patientlogin')
return render(request,'hospital/patientsignup.html',context=mydict)
error
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/admin-add-patient
Django Version: 5.1.4
Python Version: 3.13.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'hospital',
'widget_tweaks']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "C:\Users\denis\Desktop\hospitalmanagement-django5\.venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\denis\Desktop\hospitalmanagement-django5\.venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\denis\Desktop\hospitalmanagement-django5\.venv\Lib\site-packages\django\contrib\auth\decorators.py", line 60, in _view_wrapper
return view_func(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\denis\Desktop\hospitalmanagement-django5\.venv\Lib\site-packages\django\contrib\auth\decorators.py", line 60, in _view_wrapper
return view_func(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\hospitalmanagement-django5\hospital\views.py", line 360, in admin_add_patient_view
patient.assignedDoctorId=request.POST.get('assignedDoctorId')
^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\denis\Desktop\hospitalmanagement-django5\.venv\Lib\site-packages\django\db\models\fields\related_descriptors.py", line 287, in __set__
raise ValueError(
^
Exception Type: ValueError at /admin-add-patient
Exception Value: Cannot assign "'3'": "Patient.assignedDoctorId" must be a "Doctor" instance.
many many thanks
I will try solve check validation alone where I solve how to associate each patient to its doctor.