Reputation: 278
I'm trying to get the Id to filter items to show. After several tutorials and docs, I'm still not get through...
Is it possible to do it ?
Here is the form:
class MakeChecklistDone(forms.ModelForm):
def __init__(self, task, *args, **kwargs):
super(MakeChecklistDone, self).__init__(*args, **kwargs)
#title = forms.CharField(max_length = 32)
choices = forms.ModelMultipleChoiceField(
widget = forms.CheckboxSelectMultiple(),
queryset=CheckUpList.objects.all().filter(done=False, task=???)
)
class Meta:
model = CheckUpList
fields = ['choices', ]
I'm using the bellow view :
def task_detail(request, pk):
template_name = 'task/task-detail.html'
task = Task.objects.get(pk=pk)
...
if request.method == 'POST':
...
else:
form_checkUpList = MakeChecklistDone(request.POST, initial={'task': 11 })
But it seems I'm doing something wrong... Any helps will be marvellous.
Upvotes: 0
Views: 182
Reputation: 278
ok, Thanks Salma. I made a confusion between "CBV" and "View function".
def task_detail(request, pk):
template_name = 'task/task-detail.html'
task = Task.objects.get(pk=pk)
..
if request.method == 'POST':
...
else:
form_checkUpList = MakeChecklistDone(task=task, request.POST)
For the form:
class MakeChecklistDone(forms.ModelForm):
choices = forms.ModelMultipleChoiceField(widget = forms.CheckboxSelectMultiple(), queryset=None)
class Meta:
model = CheckUpList
fields = ['choices', ]
def __init__(self, task, *args, **kwargs):
super(MakeChecklistDone, self).__init__(*args, **kwargs)
self.fields['choices'].queryset = CheckUpList.objects.all().filter(done=False, task=task))
Upvotes: 0
Reputation: 321
Instead of using a view function using a view class (Create view, update view, listing v) and use the get_form_kwargs method to pass a value to the form like below:
class task_detail(LoginRequiredMixin,
UpdateView):
template_name = 'learningcenters/lc/form.html'
form_class = LearningCenterForm
queryset = CheckUpList.objects.all()
def get_object(self):
id_ = self.kwargs.get("pk")
return get_object_or_404(task_detail, id=id_)
def get_form_kwargs(self, *args, **kwargs):
kwargs = super().get_form_kwargs(*args, **kwargs)
kwargs['task'] = 11
return kwargs
In form in init:
def __init__(self, task, *args, **kwargs):
super(MakeChecklistDone, self).__init__(*args, **kwargs)
choices = forms.ModelMultipleChoiceField(
widget = forms.CheckboxSelectMultiple(),
queryset=CheckUpList.objects.all().filter(done=False, task=task)
)
Upvotes: 1