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
Related
hi i have a problem with this filter. group_to_add takes some values which should filter out the problem that I don't want those values but I want the others without those.
I would like to find a way to take those values and subtract them from others.
group_to_add = DatiGruppi.objects.filter(gruppi_scheda = scheda.id)
GruppiForm.base_fields['dati_gruppo'] = forms.ModelChoiceField(queryset = group_to_add)
I asked a similar question I leave the link
select filtering and removal if they are already present in the db
models
class Schede(models.Model):
nome_scheda = models.CharField(max_length=100)
utente = models.ForeignKey(User, on_delete = models.CASCADE,related_name = 'utente')
class DatiGruppi(models.Model):
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 Gruppi(models.Model):
nome_gruppo = models.CharField(max_length=100)
I have this tab where inside there are saved data groups that contain groups that are inside a select the correct exclusion would be
group_to_add = Gruppi.objects.exclude(dati_gruppo = 147)
but instead of 147 I have to put the id of the data group of that board
view
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:
group_to_add = Gruppi.objects.exclude(dati_gruppo = 147)
GruppiForm.base_fields['dati_gruppo'] = forms.ModelChoiceField(queryset = group_to_add)
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)
If I understand it correctly, you should use .exclude(…) [Django-doc] not .filter(…) [Django-doc]:
group_to_add = Gruppi.objects.exclude(
dati_gruppo__gruppi_scheda=scheda
)
GruppiForm.base_fields['dati_gruppo'] = forms.ModelChoiceField(queryset=group_to_add)
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')
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.
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)
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.