I'm developing a Property Management System, right now I'm working on an app named Property check, which basically saves info about inspections made on some properties.
A helpful user told me that I could achieve it using formsets. I'm trying to create a formset with my model TaskCheck. Every TaskCheck has a specific Task that belongs to one property. So this is what I've created:
views.py
def add_taskcheck(request, property_pk, pk):
tasks = Task.objects.filter(property=property_pk)
tasks_list = Task.objects.filter(property=property_pk).values('task')
TaskCheckFormset = formset_factory(TaskCheckForm, extra=0)
if request.method == 'POST':
#do something
else:
formset = TaskCheckFormset(initial=task_list)
context = {
'title':"Add Property Check",
'task':tasks,
'reference':property_pk,
'formset':formset,
}
return render(request, 'propertycheck/add-taskcheck.html', context)
My form looks like this:
In this case, the Task "Sofas: Check" does not belong to the instance property, so it shouldn't be there, and the field Task should be pre-filled as initial data.
As far as I know from what I've read here I should pass initial data as a dict list. So I created "tasks_list" with .values() and tried to pass it as initial:
tasks_list = Task.objects.filter(property=property_pk).values('task')
formset = TaskCheckFormset(initial=task_list)
So my questions are:
How can I pre fill those fields with the queryset tasks?
How can I limit the number of rows to the number of queryset tasks objects?
Firstly I need to filter the Task objects that belong to a specific property.
I've tried using Model formsets but I couldn't pass the initial data. I've also read this question but I can't initiate it inside forms.
My models.py:
class Task(models.Model):
task = models.CharField(max_length=100)
category = models.ForeignKey(Categories)
property = models.ManyToManyField(Property)
class TaskCheck(models.Model):
status = models.CharField(choices=STATUS_CHOICES, default='nd', max_length=50)
image = models.ImageField(upload_to='task_check', blank=True, null=True)
notes = models.TextField(max_length=500, blank=True)
task = models.ForeignKey(Task)
property_check = models.ForeignKey(Propertycheck)