How to filter for current object on FormView

287 views Asked by At

I'm having this urls.py

...
    url(r'^storageitem/(?P<pk>[\w]+)/merge/$', login_required(
        StorageItemMergeView.as_view()), name='storage_item_merge'),
...

with this view.py

...
class StorageItemMergeView(FormView):
    form_class = MergeStorageItemsForm
    success_url = reverse_lazy('storage_item_list')
    template_name = 'pmgmt/storageitem/merge.html'
...

As the URL might look like localhost:8000/storageitem/155/merge/ I'd like to exclude 155 from the form. I tried to define a custom queryset

queryset = StorageItem.objects.exclude(pk=kwargs["pk"])

but kwargs is seems not be present at this very point.

...
    queryset = StorageItem.objects.exclude(pk=kwargs["pk"])
NameError: name 'kwargs' is not defined

What is the correct way to create a FormView based on a model with all items beside the current one?

1

There are 1 answers

0
Dima  Kudosh On

You can add get_form_kwargs method to your view:

def get_form_kwargs(self):
     kwargs = super(ItemCreate, self).get_form_kwargs()
     kwargs.update({
         'exclude_pk' : self.kwargs['pk']
     })
     return kwargs

And filter queryset in your form field like this:

class MergeStorageItemsForm(Form):
    # Form fields
    def __init__(self, *args, **kwargs):
        exclude_pk = kwargs.pop('exclude_pk')
        super(FooForm, self).__init__(*args, **kwargs)
        if exclude_id:
            self.fields['some_field'].queryset = self.fields['some_field'].queryset.exclude(pk=exclude_pk)