Integrity error when adding manytomany relationship through intermediary table - django

class Operation(models.Model):
Operation_Name = models.CharField(max_length = 100)
class Doctor(models.Model):
Name = models.CharField(max_length = 100)
Related_Operations = models.ManyToManyField(Operation,through='Unique_Operation_Doctor_Patient_Relation')
def __str__(self):
return self.Name
class Unique_Operation_Doctor_Patient_Relation(models.Model):
# the doctor and the operation
Concerned_Doctor = models.ForeignKey(Doctor)
Concerned_Operation = models.ForeignKey(Operation)
# Attributes of the operation
Date = models.DateTimeField(db_index = True)
Tooth_Surface = models.IntegerField(db_index = True)
Amount = models.IntegerField(db_index = True)
Concerned_Patient = models.ForeignKey(Patient,db_index = True)
Idtag = models.AutoField(primary_key = True,default = 200000,db_index = True)
The following is a many to many relationship between two models Doctor and Operation through an intermediary model . I have also added a foreign key field to link it to a patient so that i can access a patient records. I created a form for the intermediary model. In this model i save the doctor and patient relationships, but i only add the relation to the patient in the view function.
class Try_Form(forms.ModelForm):
class Meta:
model = Unique_Operation_Doctor_Patient_Relation
fields = ['Concerned_Doctor','Concerned_Operation','Concerned_Patient','Date','Tooth_Surface','Amount',]
help_texts ={
'Date': ' (YYYY-MM-DD)',
}
New_Operation_Name = forms.CharField(max_length = 100)
New_Doctor_Name = forms.CharField(max_length = 100)
field_order = ['Date','Tooth_Surface','Amount','Concerned_Operation','New_Operation_Name','Concerned_Doctor','New_Doctor_Name','Concerned_Patient']
def __init__(self,*args,**kwargs):
super(Try_Form,self).__init__(*args,**kwargs)
self.fields['Concerned_Doctor'].required = False
self.fields['Concerned_Operation'].required = False
self.fields['Concerned_Patient'].required = False
def clean(self):
# The connected doctors. Creating new Doctors if they don't exist and connecting them. The same for operations.
Existing_Operation_Connection = self.cleaned_data.get('Concerned_Operation')
New_Operation_Connection = self.cleaned_data.get('New_Operation_Name')
if Existing_Operation_Connection and not New_Operation_Connection:
self.Concerned_Operation = Existing_Operation_Connection
elif not Existing_Operation_Connection and New_Operation_Connection:
Possible_New_Operation,create = Operation.objects.get_or_create(Operation_Name = New_Operation_Connection)
if not create:
self.Concerned_Operation = Possible_New_Operation
else:
self.Concerned_Operation = Possible_New_Operation
else:
raise ValidationError("Please do not add a new operation and select an existing operation in the same form.")
Existing_Doctor_Connection = self.cleaned_data.get('Concerned_Doctor')
New_Doctor_Connection = self.cleaned_data.get('New_Doctor_Name')
if Existing_Doctor_Connection and not New_Doctor_Connection:
self.Concerned_Doctor = Existing_Doctor_Connection
elif not Existing_Doctor_Connection and New_Doctor_Connection:
Possible_New_Doctor,create = Doctor.objects.get_or_create(Name = New_Doctor_Connection)
if not create:
self.Concerned_Doctor = Possible_New_Doctor
else:
self.Concerned_Doctor = Possible_New_Doctor
else:
raise ValidationError("Please do not add a new doctor and select an existing doctor in the same form.")
return super(Try_Form,self).clean()
The view function is as follows
def patient_tryform(request, pk):
if request.method == "POST":
form = Try_Form(request.POST)
if form.is_valid():
new_operation = form.save(commit = False)
connected_patient = Patient.objects.get(Patient_Id = pk)
new_operation.Concerned_Patient = connected_patient
new_operation.save()
return redirect('patient_treatmentrecord',pk = pk)
else:
form = Try_Form()
return render(request,'patient/patient_addoperation.html',{'form':form})
The error I get is for the line => new_operation.save()
IntegrityError => NOT NULL constraint failed:
patient_unique_operation_doctor_patient_relation.Concerned_Doctor_id. Although I checked with the python shell And the doctor has been created with a unique primary key.

Related

select filtering and removal if they are already present in the db

look at the picture before answering me.
that group2 is inside saved in the db with the button I open a modal that allows me to save other groups in the db and I would like that the same groups no longer appear in that select if I have already added them
form.py
class EserciziForm(forms.ModelForm):
class Meta:
model = models.DatiEsercizi
exclude = ['gruppo_single']
#fields = '__all__'
class GruppiForm(forms.ModelForm):
class Meta:
model = models.DatiGruppi
exclude = ['gruppi_scheda']
views.py
def creazione(request, nome):
scheda = get_object_or_404(Schede, nome_scheda = nome)
eserciziFormSet = formset_factory(EserciziForm, extra = 0)
if request.method == "POST":
gruppo_form = GruppiForm(request.POST, prefix = 'gruppo')
if gruppo_form.is_valid():
gruppo = gruppo_form.save(commit = False)
gruppo.gruppi_scheda = scheda
gruppoName = gruppo_form.cleaned_data['dati_gruppo']
gruppo.save()
esercizi_formset = eserciziFormSet(request.POST, prefix='esercizi')
for esercizi in esercizi_formset:
esercizi_instance = esercizi.save(commit = False)
esercizi_instance.gruppo_single = get_object_or_404(DatiGruppi, gruppi_scheda = scheda.id, dati_gruppo = gruppoName)
esercizi_instance.save()
return HttpResponseRedirect(request.path_info)
else:
gruppo_form = GruppiForm(prefix = 'gruppo')
esercizi_formset = eserciziFormSet(prefix='esercizi')
context = {'scheda' : scheda, 'gruppo_form' : gruppo_form, 'esercizi_formset': esercizi_formset}
return render(request, 'crea/passo2.html', context
models.py
class DatiGruppi(models.Model):
giorni_settimana_scelta = [
("LUNEDI","Lunedì"),
("MARTEDI","Martedì"),
("MERCOLEDI","Mercoledì"),
("GIOVEDI","Giovedì"),
("VENERDI","Venerdì"),
("SABATO","Sabato"),
("DOMENICA","Domenica")
]
giorni_settimana = MultiSelectField(choices = giorni_settimana_scelta,default = '-')
dati_gruppo = models.ForeignKey(
Gruppi,on_delete = models.CASCADE, related_name = 'dati_gruppo')
gruppi_scheda = models.ForeignKey(Schede,on_delete = models.CASCADE, related_name = 'gruppi_scheda')
class Schede(models.Model):
nome_scheda = models.CharField(max_length=100)
data_inizio = models.DateField()
data_fine = models.DateField()
utente = models.ForeignKey(User, on_delete = models.CASCADE,related_name = 'utente')
You can override a form field before instantiate it like this :
views.py
from django import forms
if request.method == "POST":
# Post logic here
else:
# We try to retrieve group that the current user is not yet in.
# Not your logic, but to sum up, you have to retrieve the groups
# which had not yet been added.
# Use a filter that permit you to retrieve only groups which had not yet been added.
group_to_add = Group.objects.filter(...)
GruppiForm.base_fields['group_field'] = forms.ModelChoiceField(
queryset=group_to_add)
# Instantiate the form now
# In this form, the choices are only those contained in the group_to_add queryset
form = GruppiForm(prefix = 'gruppo')

Update set of fields in django model passed in request.POST

This is my Model class
class SubJobs(models.Model):
id = models.AutoField(primary_key = True)
subjob_name = models.CharField(max_length=32,help_text="Enter subjob name")
subjobtype = models.ForeignKey(SubjobType)
jobstatus = models.ForeignKey(JobStatus, default= None, null=True)
rerun = models.ForeignKey(ReRun,help_text="Rerun")
transfer_method = models.ForeignKey(TransferMethod,help_text="Select transfer method")
priority = models.ForeignKey(Priority,help_text="Select priority")
suitefiles = models.ForeignKey(SuiteFiles,help_text="Suite file",default=None,null=True)
topofiles = models.ForeignKey(TopoFiles,help_text="Topo file",default=None,null=True)
load_image = models.NullBooleanField(default = True,help_text="Load image")
description = models.TextField(help_text="Enter description",null=True) command = models.TextField(help_text="Command",null=True)
run_id = models.IntegerField(help_text="run_id",null=True)
pid_of_run = models.IntegerField(help_text="pid_of_run",null=True)
hold_time = models.IntegerField()
created = models.DateTimeField(default=timezone.now,null=True)
updated = models.DateTimeField(default=timezone.now,null=True)
finished = models.DateTimeField(null=True)
The user might want to update a entry and may choose to update only few fields among these. How do I write a generic update statement that would update only the fields that were passed?
I tried this.
def update_subjob(request):
if (request.method == 'POST'):
subjobs_subjobid = request.POST[('subjob_id')]
post_data = request.POST
if 'subjob_name' in post_data:
subjobs_subjobname = request.POST[('subjob_name')]
if 'subjob_type' in post_data:
subjobs_subjobtype = request.POST[('subjob_type')]
if 'rerun_id' in post_data:
subjobs_rerun_id = request.POST[('rerun_id')]
if 'priority_id' in post_data:
subjobs_priority_id = request.POST[('priority_id')]
if 'transfer_method' in post_data:
subjobs_transfermethod = request.POST[('transfer_method')]
if 'suitefile' in post_data:
subjob_suitefile = request.POST[('suitefile')]
if 'topofile' in post_data:
subjob_topofile = request.POST[('topofile')]
try:
subjobinstance = SubJobs.objects.filter(id=subjobs_subjobid).update(subjob_name=subjobs_subjobname,
updated=datetime.now())
except Exception as e:
print("PROBLEM UPDAING SubJob!!!!")
print(e.message)
How do I write a generic update to update only those fields which are sent in request.POST?
You'd better use Forms. But if you insist on your code it could be done like this.
Suppose you have variable field_to_update where every field that you are waiting in request is listed.
subjobs_subjobid = request.POST[('subjob_id')]
field_to_update = ('subjob_name','subjob_type', 'rerun_id', 'priority_id', 'transfer_method', 'suitefile', 'topofile')
post_data = request.POST
to_be_updated = {field: post_data.get(field) for field in field_to_update if field in post_data}
# then you need to get the object, not filter it
try:
subjobinstance = SubJobs.objects.get(id=subjobs_subjobid)
subjobinstance.update(**to_be_updated, updated=datetime.now())
except ObjectDoesNotExist: # from django.core.exceptions
print('There is no such object') # better to use logger
except Exception as e:
print("PROBLEM UPDAING SubJob!!!!")
print(e.message)

Foreign Key related form Saving in Django

My Models are look like .....
Student(models.Model):
name = models.CharField(max_length = 60, blank = False)
r_no = models.CharField(max_length = 60, blank = False)
created_date = models.DateTimeField(null = False, blank = False, default = datetime.datetime.now())
StudentPotential(models.Model):
aka_name = models.CharField(max_length = 60, blank = True)
-----
-----
StudentCorrespondence(models.Model):
student = models.ForeignKey('Student', related_name = "Student_FK")
student_p = models.ForeignKey('Student', related_name = "Student_FK")
emailed_date = models.DateTimeField(null = True, blank = True)
phoned_date = models.DateTimeField(null = True, blank = True)
My Form in form.py
class StudentPotentialForm (forms.ModelForm):
class Meta:
model = StudentPotential
class StudentCorrespondenceForm(forms.ModelForm):
class Meta:
model = StudentCorrespondence
exclude = ('student', 'student_p')
Finally My view.py
def add_student_company_potential(request, student_id):
from cdradmin.forms import StudentPotentialForm, StudentCorrespondenceForm
if request.method == 'POST':
### HOW TO SAVE THE two from for the student have its it 'student_id' ####
else:
StudentPotentialForm = StudentPotentialForm()
StudentCorrespondenceForm = StudentCorrespondenceForm()
context = {'StudentCorrespondenceForm':StudentCorrespondenceForm, "StudentPotentialForm":StudentPotentialForm}
return render_to_response('cdradmin/studentform.html', context, context_instance = RequestContext(request))
Once the data is post to the view, How can i able to save this data for the student has his/her id is 'student_id'
You can try this
if request.method == 'POST':
spf = StudentPotentialForm(request.POST)
if spf.is_valid():
osp = spf.save()
else :
#raise error
student = Student.objects.get(id=student_id)
scf = StudentCorrespondenceForm(request.POST)
if scf.is_valid():
osc = scf.save(commit=False)
osc.student = student
osc.student_p = osp
osc.save()
else:
# raise error.

django updating user profile form

forms.py
class UserProfileForm(forms.ModelForm):
phone = forms.CharField(max_length = 15,widget = forms.TextInput(attrs = {'placeholder':'Enter mobile no. ','class':''}))
profession = forms.CharField(max_length= 50,widget = forms.Select(choices = PROFESSION_CHOICES,attrs = {'class':''}))
#email = forms.EmailField(label='Email address',max_length = 75,widget = forms.TextInput(attrs={'placeholder':'Email address.','class':''}))
sex = forms.CharField(max_length = 20,label="I am :",widget=forms.Select(choices=SEX_CHOICES,attrs = {'class':''}))
first_name = forms.CharField(max_length = 50,widget = forms.TextInput(attrs={'placeholder':'Please enter your real name.','class':''}))
last_name = forms.CharField(max_length = 50,widget = forms.TextInput(attrs={'placeholder':'Enter last name.','class':''}))
location = forms.CharField(max_length = 50,widget = forms.TextInput(attrs={'placeholder':'Enter your current location','class':''}))
def clean_first_name(self):
first_name = self.cleaned_data['first_name']
if first_name == '':
raise forms.ValidationError("This field is required.")
return first_name
def save(self,*args,**kw):
self.instance.first_name = self.cleaned_data.get("first_name")
self.instance.last_name = self.cleaned_data.get("last_name")
self.instance.sex = self.cleaned_data.get("sex")
self.instance.location = self.cleaned_data.get("location")
self.instance.profession = self.cleaned_data.get("profession")
self.instance.phone = self.cleaned_data.get("phone")
self.instance.save()
return self.instance
class Meta:
model = User
fields = ('username','first_name','last_name','phone','sex','profession','location')
views.py
def profile(request,nav="profile",template="profile.html",context = {},extra_context = None):
if request.POST:
if 'profileFormSubmit' in request.POST:
pform = UserProfileForm(request.POST,instance = request.user)
if pform.is_valid():
try:
user = pform.save()
return redirect(profile,nav="profile")
except RuntimeError as e:
return HttpResponse(e)
error
The User could not be changed because the data didn't validate.
line
user = super(UserProfileForm,self).save(*args,**kw)
doubt
what changes am i supposed to make to get rid of this error
how am i supposed to change the , i have tried removing all the clean_field form methods , but still getting the same error , please help , thanks in advance.
You are calling save on your form before you clean. And you are calling save twice. Once at the start of the form save. And once at the end.
pform.is_valid() returns a boolean that you never check.
docs on modelforms
The form wasn't validating because I was using 'username' in my meta class of the UserProfileForm, which wasn't supposed to be there.

IntegrityError error while saving value of to foreign key in django

Hey folks i am getting integrity error while saving my views .Please tell me what i am doing wrong
Here is my django model
class Ruleinfo(models.Model):
rule = models.IntegerField(null=False)
From = models.IPAddressField(null=True)
to = models.IPAddressField(null=True)
priority = models.ForeignKey('Priority',related_name='pri_no')
cisp =models.ForeignKey('Priority',related_name = 'CISP_no')
def __unicode__(self):
return u'%s' %(self.rule)
class Priority(models.Model):
pri = models.IntegerField(null = True)
Ruleno = models.ForeignKey('Ruleinfo',related_name = 'ruleno_no')
CISP = models.IntegerField(null = True)
def __unicode__(self):
return u'%s ' % (self.priority)
My model form is looking like .
class RuleInfoForm(ModelForm):
class Meta:
model = Ruleinfo
fields = ("rule","From","to")
here is my views.py
def multiwanrule_info(request):
data = {}
no_of_isp = MultiWAN.objects.all()
try:
form = RuleInfoForm(request.POST)
except:
pass
print "----------------------------printing form"
print form
if form.is_valid():
rl_frm = form.save(commit=False)
get_priorities = request.POST.getlist('priority')
get_cisp_info = request.POST.getlist('cisp')
rule_object = Ruleinfo()
for get_pri,get_ci in zip(get_priorities,get_cisp_info,):
pri_object = Priority.objects.get_or_create(Ruleno = rule_object)
pri_object.pri = get_pri
pri_object.CISP = get_ci
rl_frm.save()
else:
form = RuleInfoForm()
data['form'] = form
data['number_of_isp'] = no_of_isp
return render_to_response('networking.html',data)
I am getting the above error along this
networking_priority.Ruleno_id may not be NULL
help me out so that i could get back on track .
rule_object = Ruleinfo()
This just instantiates a new model object. It is not saved or assigned values. Since it is not saved it does not have an id value.
assigning your rule_object values: rule, from, to, priority, and cisp values, should fix your problem.