Foreign Key related form Saving in Django - 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.

Related

django creating new record when update existing record

My models of Employee registration is as follow.
class EmployeeRegistration(models.Model):
#Departmental Details
EmpId = models.IntegerField(verbose_name='EmpId')
EmpImage = models.ImageField(default='default.png',upload_to='profile_pic/%Y/%m/%d')
EmpSafetyCard= models.ImageField(default='default.png',upload_to='profile_pic/%Y/%m/%d')
Site = models.ForeignKey(Site,on_delete=models.CASCADE,max_length=150,verbose_name='Site')
Department = models.ForeignKey(Department,on_delete=models.CASCADE,max_length=150,verbose_name='Department')
Category = models.ForeignKey(Category,on_delete=models.CASCADE,max_length=150,verbose_name='Category')
Designation = models.ForeignKey(Designation,on_delete=models.CASCADE,max_length=150,verbose_name='Designation')
PfApplicable = models.BooleanField(default = True,verbose_name='Pf Applicable')
EsiApplicable = models.BooleanField(default = True,verbose_name='Esic Applicable')
Uan = models.PositiveIntegerField(null = True,verbose_name='Uan')
Esic = models.PositiveIntegerField(null = True,verbose_name='Esic')
AttendenceAward = models.BooleanField(default = True)
AttendenceAllowance = models.BooleanField(default = True)
ProfesionalTax = models.BooleanField(default = False)
Name = models.CharField(max_length=150,verbose_name='Name')
Father = models.CharField(max_length=150,verbose_name='Father')
Dob = models.DateField()
Male = models.BooleanField(default = True)
Female = models.BooleanField(default = False)
MaritalStatus = models.BooleanField(default = True)
Address = models.CharField(max_length=200,verbose_name='Address')
Aadhar = models.PositiveIntegerField(null=True)
pan = models.CharField(max_length=10)
choices = [('Working','WORKING'),('NotWorking','NOT WORKING'),('Leave','Leave')]
Status = models.CharField(choices=choices,blank = False,max_length=10,verbose_name='Status')
Doj = models.DateField(default = date.today)
Doe = models.DateField(blank = True,verbose_name = 'Doe',null = True)
def __str__(self):
return f'{self.Name}({self.EmpId})'
def save(self):
super().save()
empimg = Image.open(self.EmpImage.path)
empsafetycard = Image.open(self.EmpSafetyCard.path)
if empimg.height>300 or empimg.width>300:
output_size = (300,300)
empimg.thumbnail(output_size)
empimg.save(self.EmpImage.path)
if empsafetycard.height>300 or empsafetycard.width>300:
output_size = (300,300)
empsafetycard.thumbnail(output_size)
empsafetycard.save(self.EmpSafetyCard.path)
This is my newEmployeeForm code
class newEmployeeForm(forms.ModelForm):
class Meta:
model = EmployeeRegistration
fields = '__all__'
labels ={
'EmpImage':'Upload Employee Image',
'EmpSafetyCard':'Upload Safety Card',
'Dob':'Date of Birth',
'Doj':'Date of Joining',
'Doe':'Date of Exit'
}
widgets = {
'Dob':DateInput(),
'Doj': DateInput(),
'Doe': DateInput()
}
This is my View for regitering new employee
def registration_view(request,id=0):
form = newEmployeeForm()
record = RecordsId.objects.all()
empid = 0
for data in record:
empid = data.EmpId
emp_id = empid+1
if(empid!=0 or empid==0):
get_emp = RecordsId.objects.get(EmpId=empid)
EmployeeId={"EmpId":emp_id}
print(request.POST)
if(request.method == 'POST'):
if(id==0):
form = newEmployeeForm(request.POST or None,request.FILES,initial=EmployeeId)
print("id= 0")
else:
print(id)
employee = EmployeeRegistration.objects.get(pk=id)
form = newEmployeeForm(instance=employee)
if form.is_valid():
print("valid")
get_emp.EmpId = emp_id
get_emp.save()
form.save()
print("saved")
form = newEmployeeForm(initial=EmployeeId)
messages.success(request,'Successfully Updated')
return redirect('emplist')
else:
print("Form is not valid")
context = {
'form':form,
"contact":"active"
}
return render(request,"employee/NewEmployee.html",context)
I have a view for registering new employee at the same time in the same view i am updating the records of employee. But when i am trying to update the existing record. It is creating new record. i don't know why this is happening. Please help me.

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')

Django multiplechoicefield always renders None

I made a multiplechoicefield form (to ask what category user wants to select), but i can't get the answer back...it always renders "None".
I added some 'print' in the code to be sure that it was the problem and it is.
I don't understand why.
forms.py:
class Category(forms.ModelForm):
class Meta:
model = Auctions
fields = ("category",)
#fields = ('category',)
#widgets = {'category' : forms.RadioSelect()}
catform = forms.MultipleChoiceField(choices=fields, widget=forms.CheckboxSelectMultiple())
models.py
'''
class Auctions(models.Model):
Category = [('FASHION', 'Fashion'),('TOYS','Toys'),('ELECTRONICS','Electronics'),('HOME','Home')]
ID_auction = models.AutoField(primary_key = True)
title = models.CharField(max_length = 80)
description = models.TextField()
startingbid = models.IntegerField()
image = models.URLField(blank = True)
category = models.CharField(max_length = 80, choices = Category)
author_id = models.ForeignKey(User,on_delete = models.CASCADE, related_name = "auteur")
highest_bid = models.IntegerField("Bid", blank = True, null = True)
buyer = models.ForeignKey(User, on_delete = models.CASCADE, related_name = "acheteur")
active = models.BooleanField(default=True)
'''
views.py
'''
def filter_cat(request):
if request.method == "POST":
form = Category(request.POST)
print(form)
if form.is_valid():
cat = form.cleaned_data.get("catform")
print(cat)
auctions = Auctions.objects.filter(category = cat)
return render(request, "auctions/index.html",{
'active_listing' : auctions, 'cat' : cat
})
else :
form = Category()
return render(request, "auctions/filter_cat.html",{'form' : form})
'''
when I select FASHION for example i get this on the terminal :
for print(form):
Category:
---------
Fashion
Toys
Electronics
Home
for print(cat):
None

Integrity error when adding manytomany relationship through intermediary table

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.

Create, Update and Delete in Django

I am only creating entries for some fields in my models.py at the moment. Now I want to add Delete and Update functions to my Application. Let's take this Model for example:
class todoList(models.Model):
trainee = models.ForeignKey(trainee, verbose_name = "Azubi", blank = True)
todoLearningObjective = models.ManyToManyField(learningObjective, verbose_name = "Lernziel", blank = True, null = True)
tasks = models.TextField(verbose_name = 'Aufgaben')
levyDate = models.DateField(verbose_name = 'Abgabedatum', blank = True, null = True)
priority = models.IntegerField(verbose_name = 'Prioritaet', blank = True, null = True)
class Meta:
verbose_name = "To-Do Liste"
verbose_name_plural = "To-Do Listen"
The matching Form:
class todoListForm(forms.Form):
formtrainee = forms.IntegerField(required = False)
formtodoLearningObjective = forms.CharField(required = False)
formtasks = forms.CharField(required = True)
formlevyDate = forms.DateField(required = False)
formpriority = forms.IntegerField(required = False)
And the View:
def todo(request):
trainee_objects = trainee.objects.all()
usernameID = 1
for traineeUser in trainee_objects:
if traineeUser.username == request.user.username:
usernameID = traineeUser.id
if request.method == 'POST':
forms = todoListForm(request.POST)
if forms.is_valid():
formtasks = forms.cleaned_data['formtasks']
formtodoLearningObjective = forms.cleaned_data['formtodoLearningObjective']
formlevyDate = forms.cleaned_data['formlevyDate']
formpriority = forms.cleaned_data['formpriority']
neueTodo=todoList(tasks=formtasks, levyDate=formlevyDate, priority=formpriority, trainee_id = usernameID)
neueTodo.save()
for todo in learningObjective.objects.filter(learningObjectives=formtodoLearningObjective):
neueTodo.todoLearningObjective.add(todo)
else:
forms = todoList()
return render(request, 'todo.html', {'todo': todoList.objects.all(), 'Lernziel': learningObjective.objects.all()})
As you can see, I have M to M relations and I am just creating new entries. My question is now: Do I have to create a new update and delete method for every model ? Or is there an easier way ? I want to keep my project DRY although I probably failed that mission already. It would be awesome if you could give me example or documentation on how Deleting and Updating in Django works all in all.
You have built class based views for that.
from django.views.generic import CreateView,UpdateView,DeleteView
class Todo(CreateView):
formClass = todoListForm
template_name = 'your_template_name.html'
More information