Query django foreignkey relationship - django

I am developing an audit management information system where I can record all finding related to an audit. I have models with foreignkeys relationship. How do I see all findings with a particular assignment and audit_title and unit?
See relevant codes below.
model.py content
class Unit(models.Model):
unit_name = models.CharField(max_length=30, blank=True, null=True)
def __unicode__(self):
return self.unit_name
class Assignment(models.Model):
assignment_name = models.CharField(max_length=30, blank=True, null=True)
def __unicode__(self):
return self.assignment_name
class Task(models.Model):
task_title = models.CharField(max_length=35, blank=True, null=True)
return self.task_title
class Finding(models.Model):
assignment = models.ForeignKey(Assignment, blank=True, null=True)
audit_title = models.ForeignKey(Task, blank=True, null=True)
auditor = models.ManyToManyField(User, blank=True)
unit = models.ForeignKey(Unit, blank=True, null=True)
audit_period = models.DateField(auto_now_add=False, auto_now=False, blank=True, null=True)
contact_person = models.CharField('Contact Person', max_length=500, blank=True, null=True)
finding = models.TextField('Detail Finding', max_length=500, blank=True, null=True)
be = models.CharField(max_length=30, blank=True, null=True)
form.py
class FindingSearchForm(forms.ModelForm):
class Meta:
model = Finding
fields = ['assignment',
'audit_title',
'unit',
'be',
]
Am I have the following in my views.py but I have this error invalid literal for int() with base 10: ''
views.py content
def finding_list(request):
title = 'List of Finding'
queryset = Finding.objects.all()
queryset_count = queryset.count()
form = FindingSearchForm(request.POST or None)
context = {
"title": title,
"form": form,
"queryset_count": queryset_count,
}
if request.method == 'POST':
unit = form['unit'].value()
audit_title = form['audit_title'].value()
assignment = form['assignment'].value()
queryset = Finding.objects.all().order_by('-timestamp').filter(be__icontains=form['be'].value(),
unit_id=unit,
assignment_id=assignment,
audit_title_id=audit_title,)

if request.method == 'POST':
unit = form['unit'].value()
audit_title = form['audit_title'].value()
assignment = form['assignment'].value()
queryset = Finding.objects.all().order_by('-timestamp').filter(be__icontains=form['be'].value()
)
if (unit != ''):
queryset = queryset.filter(unit_id=unit)
if (audit_title != ''):
queryset = queryset.filter(audit_title_id=audit_title)
if (assignment != ''):
queryset = queryset.filter(assignment_id=assignment)

Related

AttributeError: 'NoneType' object has no attribute 'is_nightly'

I've got an error on the expression with below defined function on serializer.py and i have an ordering items with different calculation with posting on nightly basis and once posting.
if special_order_item.special_item.is_nightly == True: AttributeError: 'NoneType' object has no attribute 'is_nightly'
the error was referred to "if special_order_item.special_item.is_nightly == True:"
models.py
class SpecialsItem(models.Model):
hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE, related_name="special_items", null=False, blank=False)
code = UpperCaseCharField(max_length=50, blank=True, null=True)
desc = models.CharField(max_length=100, blank=True, null=True)
pms_tran_code = UpperCaseCharField(max_length=50, blank=True, null=True)
unit_price = models.DecimalField(max_digits=20, decimal_places=10, default=0)
is_nightly = models.BooleanField(default=True)
inventory = models.IntegerField(default=0)
image = models.ImageField(upload_to='img', blank=True, null=True, default='')
serializers.py
class SpecialsOrderItemsSerializer(serializers.ModelSerializer):
special_item = SpecialItemSerializer(many=False, read_only=True)
amount = serializers.SerializerMethodField(method_name='sub_total')
class Meta:
model = SpecialOrderItems
fields = [
'id',
'reservation',
'special_item',
'qty',
'amount',
'created_by',
'updated_by'
]
def sub_total(self, special_order_item:SpecialOrderItems): # definedname : model_object
if special_order_item.special_item.is_nightly == True:
items_total = special_order_item.qty * special_order_item.special_item.unit_price * special_order_item.reservation.night
return items_total
else:
items_total = special_order_item.qty * special_order_item.special_item.unit_price
return items_total
Looking a expertise for who have experiencing to figure out a solution

django - How can I prefill formset forms data using database query result?

I am creating a student attendance form where need to get details of student name, student class and Id from student model based on teacher selecting student class in one form. I have tried using initial by using for loop on query data to prefill the form in formset, however it populates data for one record only. Below is the code for forms.py, models and views.py. Can someone help on this
forms.py
class student(models.Model):
studentid = models.AutoField(primary_key=True)
Gender = models.CharField(max_length=6, choices=gender, null=True)
Name = models.CharField(max_length=100, null=True)
DOB = models.DateField(null=True)
Image = models.ImageField(null=True, upload_to='images')
Status = models.CharField(max_length=10, choices=statchoice, null=True)
Father_name = models.CharField(max_length=100, null=True)
Mother_name = models.CharField(max_length=100, null=True)
Address = models.CharField(max_length=200, null=True)
Contact_no = models.IntegerField(null=True)
Email = models.EmailField(null=True)
Admission_class = models.CharField(max_length=40, null=True, choices=grade)
Admission_date = models.DateField(null=True)
Current_class = models.CharField(max_length=40, null=True, choices=grade)
Leaving_date = models.DateField(null=True, blank=True)
objects = models.Manager()
def __str__(self):
return str(self.studentid)
class student_attendance(models.Model):
Student_ID = models.CharField(max_length=100, null=True)
Student_Name = models.CharField(max_length=100, null=True)
Student_class = models.CharField(max_length=100, null=True, choices=grade)
Attendance_date = models.DateField(null=True, auto_now_add=True, blank=True)
Attendance_status = models.CharField(choices=attendance, null=True, max_length=10)
objects = models.Manager()
Views.py
def student_attend(request):
if request.method == 'POST':
data = request.POST.get('studentGrade')
formset_data = student.objects.filter(Current_class=data)
AttendanceFormSet = formset_factory(std_attendance, extra=(len(formset_data))-1)
for element in formset_data:
formset = AttendanceFormSet(initial=[
{'Student_ID': element.studentid, 'Student_Name':element.Name, 'Student_class':element.Current_class, 'Attendance_status':"Present"}
])
param = {'formset':formset}
return render(request, 'home/student_attendance.html', param)
return render(request, 'home/student_attendance.html')
form.py:
class student_register(ModelForm):
class Meta:
model = student
fields = '__all__'
class std_attendance(ModelForm):
class Meta:
model = student_attendance
fields = '__all__'
Each iteration in your loop you override the formset, that is why only a single form is filled, you need to fill the param with all the forms inside the loop this way:
initial = []
for element in formset_data:
initial.append({'Student_ID': element.studentid, 'Student_Name':element.Name, 'Student_class':element.Current_class, 'Attendance_status':"Present"}
formset = AttendanceFormSet(initial=initial)

Django inlineformset: PK missing in subform -> form_set.is_valid() = False

I have followed this tutorial to implement inlneformset.
CreateView works (data is registered in database) but UpdateView doesn't.
UpdateView is correctly displayed with correct data.
But it seems like subform (application inlineformset) is never valid and I don't understand why?
forms.py:
NAME = Thesaurus.options_list(2,'fr')
ACCESS = Thesaurus.options_list(3,'fr')
ApplicationFormset = inlineformset_factory(
Utilisateur, Application,
fields=('app_app_nom','app_dro'),
widgets={
'app_app_nom': forms.Select(choices=NAME),
'app_dro': forms.Select(choices=ACCESS)
},
extra=3,
can_delete=True,
)
models.py:
class Projet(SafeDeleteModel):
_safedelete_policy = SOFT_DELETE_CASCADE
pro_ide = models.AutoField(primary_key = True)
pro_nom = models.IntegerField("Nom du projet", null=True, blank=True)
pro_log = models.CharField("Log utiisateur", max_length=20, null=True, blank=True)
pro_dat = models.DateTimeField("Date log",auto_now_add=True)
pro_act = models.IntegerField("Projet en cours ?", null=True, blank=True)
log = HistoricalRecords()
class Meta:
db_table = 'tbl_pro'
verbose_name_plural = 'Projets'
ordering = ['pro_ide']
permissions = [
('can_add_project','Can add project'),
]
class Utilisateur(SafeDeleteModel):
_safedelete_policy = SOFT_DELETE_CASCADE
uti_ide = models.AutoField(primary_key = True)
pro_ide = models.ForeignKey(Projet, on_delete = models.CASCADE) # related project
uti_nom = models.CharField("Nom", max_length=20, null=True, blank=True)
uti_pre = models.CharField("Prénom", max_length=20, null=True, blank=True)
uti_mai = models.CharField("Email", max_length=40, null=True, blank=True)
uti_sit = models.CharField("Equipe", max_length=20, null=True, blank=True)
uti_pro = models.CharField("Fonction/profil", max_length=200, null=True, blank=True)
uti_dem_dat = models.DateTimeField("Date demande",auto_now_add=True, null=True, blank=True)
uti_val = models.IntegerField("Demande validée ?", null=True, blank=True)
uti_val_dat = models.DateTimeField("Date validation",auto_now_add=True, null=True, blank=True)
uti_log = models.CharField("Log utilisateur", max_length=20, null=True, blank=True)
uti_dat = models.DateTimeField("Date log",auto_now_add=True, null=True, blank=True)
log = HistoricalRecords()
#classmethod
def options_list(cls,pro_ide):
projet = Projet.objects.get(pro_ide=pro_ide)
utilisateurs = Utilisateur.objects.filter(pro_ide=projet.pro_ide)
the_opts_list = [(utilisateur.uti_ide, utilisateur.uti_nom+', '+utilisateur.uti_pre) for utilisateur in utilisateurs]
the_opts_list.insert(0, (None, ''))
return the_opts_list
class Meta:
db_table = 'tbl_uti'
verbose_name_plural = 'Utilisateurs'
ordering = ['uti_ide']
class Application(SafeDeleteModel):
_safedelete_policy = SOFT_DELETE_CASCADE
app_ide = models.AutoField(primary_key = True)
uti_ide = models.ForeignKey(Utilisateur, on_delete = models.CASCADE) # related utilisateur
app_app_nom = models.IntegerField("Nom application", null=True, blank=True)
app_dro = models.IntegerField("Droit sur application", null=True, blank=True)
app_sta = models.IntegerField("Statut (création/Modification/Suppression", null=True, blank=True)
app_log = models.CharField("Log utilisateur", max_length=20, null=True, blank=True)
app_dat = models.DateTimeField("Date log",auto_now_add=True, null=True, blank=True)
log = HistoricalRecords()
class Meta:
db_table = 'tbl_app'
verbose_name_plural = 'Applications'
ordering = ['app_ide']
class Administration(SafeDeleteModel):
_safedelete_policy = SOFT_DELETE_CASCADE
adm_ide = models.AutoField(primary_key = True)
app_ide = models.ForeignKey(Application, on_delete = models.CASCADE) # related application
adm_nom = models.CharField("Nom d'utilisateur dans l'application", max_length=20, null=True, blank=True)
adm_dem = models.IntegerField("Demande traitée ?", null=True, blank=True)
adm_dem_dat = models.DateTimeField("Date traitement de la demande",auto_now_add=True)
adm_log = models.CharField("Log utilisateur", max_length=20, null=True, blank=True)
adm_dat = models.DateTimeField("Date log",auto_now_add=True)
log = HistoricalRecords()
class Meta:
db_table = 'tbl_adm'
verbose_name_plural = 'Adminitrations'
ordering = ['adm_ide']
permissions = [
('can_manage_project','Can manage project'),
]
UpdateView:
class UtilisateurUpdateView(UpdateView):
model = Utilisateur
fields = ['uti_nom','uti_pre','uti_mai','uti_sit','uti_pro']
def get_context_data(self, **kwargs):
data = super().get_context_data(**kwargs)
if self.request.POST:
data["utilisateur"] = self.request.user.username
data["application"] = ApplicationFormset(self.request.POST, instance=self.object)
else:
data["application"] = ApplicationFormset(instance=self.object)
return data
def form_valid(self, form):
context = self.get_context_data()
application = context["application"]
self.object = form.save()
self.object.save()
if application.is_valid(): # ***** NEVER VALID *****
application.instance = self.object
print('application.instance',application.instance)
application.app_app_nom = application.instance.cleaned_data['app_app_nom']
application.app_dro = application.instance.cleaned_data['app_dro']
application.app_log = context["utilisateur"]
application.uti_ide = 1
application.save()
return super().form_valid(form)
def get_success_url(self):
return reverse("project:index")
I have resolve my problem: I forget to insert form_set id in my html template (app_ide in my case)

How do I make sure entered integer is greater than current value before updating model field?

I am using a form that saves to one model to update the most current mileage which is stored in another model. I want to make sure the mileage entered is > or = the current mileage. I havent been able to figure out the right validation or where to write the validation.
I have tried an if statement in the form_valid() of the CreateView and a save() method in the model.
Models.py
class Vehicle(models.Model):
name = models.CharField(blank=True, max_length=100)
make = models.CharField(blank=True, max_length=100)
model = models.CharField(blank=True, max_length=100)
year = models.IntegerField(blank=True, null=True)
vin = models.CharField(blank=True, max_length=17)
gvw = models.IntegerField(blank=True, null=True)
license_plate = models.CharField(blank=True, max_length=100)
purchase_date = models.DateField()
current_mileage = models.IntegerField(blank=True, null=True)
class Meta:
ordering = ['name']
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('vehicles:vehicle_detail', kwargs={'pk':self.pk})
#property
def get_current_mileage(self):
return self.current_mileage
class FuelEntry(models.Model):
vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE)
date = models.DateTimeField(auto_now_add=True)
fuel_choices = (
('EMPTY', 'Empty'),
('1/8', '1/8'),
('1/4', '1/4'),
('1/2', '1/2'),
('3/4', '3/4'),
('FULL', 'Full'),
)
current = models.CharField(max_length=5, choices=fuel_choices)
after = models.CharField(max_length=5, choices=fuel_choices, blank=True)
gallons = models.DecimalField(decimal_places=2, max_digits=5, blank=True, default='0')
cost = models.DecimalField(decimal_places=2, max_digits=5, blank=True, default='0')
mileage = models.IntegerField(blank=False)
user = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
ordering = ['-date', 'vehicle']
def __str__(self):
return self.vehicle.name
def get_absolute_url(self):
return reverse('fuellog:entry_detail', kwargs={'pk':self.pk})
Views.py
class CreateEntry(CreateView):
model = FuelEntry
fields = ('vehicle', 'current', 'after', 'gallons', 'cost', 'mileage')
def form_valid(self,form):
self.object = form.save(commit=False)
self.object.user = self.request.user
vehicle_id = self.object.vehicle.pk
mileage = self.object.mileage
self.object.save()
current_mileage = Vehicle.objects.filter(id=vehicle_id).get('current_mileage')
if current_mileage > mileage:
raise ValidationError('Incorrect mileage reading')
Vehicle.objects.filter(id=vehicle_id).update(current_mileage=mileage)
return super().form_valid(form)
ValueError at /fuel/new
too many values to unpack (expected 2)

Populate combos in Django and initialize them with a foreign key

I need to populate two combos in a ModelForm, and I would like to initialize them with the current value of each foreign key.
My models are:
class Alumno(models.Model):
idalumno = models.AutoField(primary_key=True)
padre_idpadre = models.ForeignKey('Padre', models.DO_NOTHING, db_column='padre_idpadre', blank=True, null=True)
curso_idcurso = models.ForeignKey('Curso', models.DO_NOTHING, db_column='curso_idcurso')
nombre = models.CharField(max_length=45, blank=True, null=True)
class Meta:
db_table = 'alumno'
class Curso(models.Model):
idcurso = models.IntegerField(primary_key=True)
nombrecurso = models.CharField(max_length=45, blank=True, null=True)
class Meta:
db_table = 'curso'
class Padre(models.Model):
idpadre = models.AutoField(primary_key=True)
socio = models.NullBooleanField(blank=True, null=True)
nombre = models.CharField(max_length=45, blank=True, null=True)
primerapellido = models.CharField(max_length=45, blank=True, null=True)
segundoapellido = models.CharField(max_length=45, blank=True, null=True)
class Meta:
db_table = 'padre'
This is my Form in forms.py:
class AlumnoForm(forms.ModelForm):
padre = PadreModelChoiceField(queryset=Padre.objects.all(), initial=**XXXXXXXXX**) #I would like to init here with the value of the FK
curso = CursoModelChoiceField(queryset=Curso.objects.all(), initial=**XXXXXXXXXX**) #And here too
class Meta:
model = Alumno
fields = ('nombre','padre','curso',)
labels = {
'nombre': 'Nombre',
'padre': 'Padre',
'curso': 'Curso',
}
In views.py
def alumno_editar(request, pk):
alumno = get_object_or_404(Alumno, pk=pk)
if request.method == "POST":
form = AlumnoForm(request.POST, instance=alumno)
if form.is_valid():
alumno = form.save(commit=False)
alumno.save()
return redirect('alumno_listar')
else:
form = AlumnoForm(instance=alumno)
return render(request, 'administration/alumno_editar.html', {'form': form})
What should I write in the part XXXXXXXXXX of the code.
It could be misconception but I'm think is a common operation, althought I don't find it.