hi all,
i’m trying using manytomanyfield in my model
models.py
class Doctor(models.Model):
user=models.OneToOneField(User,on_delete=models.CASCADE)
status=models.BooleanField(default=True)
class Patient(models.Model):
user=models.OneToOneField(User,on_delete=models.CASCADE)
assignedDoctorId = models.ManyToManyField(Doctor,default=None)
status=models.BooleanField(default=False)
form.py
class PatientForm(forms.ModelForm):
assignedDoctorId = forms.ModelMultipleChoiceField(
queryset=models.Doctor.objects.all(),
widget=forms.CheckboxSelectMultiple
)
class Meta:
model=models.Patient
}
when I click on buttons and submit the form the code return to me
hospital.Doctor.None
while I check the checkboxes.
I cannot undestand why.
secondly I would like return the list of patient.assignedDoctorId_id
but I don’t know how.
many thanks
Please post the complete form and view where you are processing this form.
views.py
@login_required(login_url='adminlogin')
@user_passes_test(is_admin_or_doctor)
def update_patient_data_view(request,pk):
patient=models.Patient.objects.get(id=pk)
user=models.User.objects.get(id=patient.user_id)
doctor = [{'id': i.id, 'doctor':i.get_name} for i in models.Doctor.objects.all()]
patientExtraData = {'password':patient.get_patient_password,'assignedDoctorId':patient.get_doctor_id}
userForm=forms.PatientUserForm(instance=user)
patientForm=forms.PatientForm(instance=patient)
mydict={'userForm':userForm,'patientForm':patientForm,'doctor':doctor,'patientExtraData':patientExtraData,'patientID':pk}
if request.method=='POST':
userForm=forms.PatientUserForm(request.POST,instance=user)
patientForm=forms.PatientForm(request.POST,instance=patient)
if userForm.is_valid() and patientForm.is_valid():
user=userForm.save()
user.set_password(user.password)
user.save()
patient=patientForm.save(commit=False)
patient.status=True
print(patient.assignedDoctorId)
patient.save()
mydictReturn={'userForm':userForm,'patientForm':patientForm,'patientID':pk}
return render(request,'hospital/admin2patient/admin_update_patient.html',context=mydictReturn)
else:
print(userForm.errors, patientForm.errors)
return render(request,'hospital/admin2patient/admin_update_patient_data.html',context=mydict)
while forms.py
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.ModelMultipleChoiceField(
queryset=models.Doctor.objects.all(),
widget=forms.CheckboxSelectMultiple
)
class Meta:
model=models.Patient
fields=['assignedDoctorId']
in html file instead
<div class="form-group">
{% render_field patientForm.assignedDoctorId class="form-control" placeholder="dottore" %}
</div>
See the section on saving many-to-many relationships in ModelForms when using commit=False
at Creating forms from models | Django documentation | Django