'Django - Can I delete an instance of object from a choices selection set (ModelChoiceField)?

I am newbie in the Django world, so i am wondering if its possible to get an instance from a selection set (choice field) and then delete it.

In my case I want to pick a Profile, and then delete it.

enter image description here

views.py

class SelectProfileFormView(views.FormView, LoginRequiredMixin):
    form_class = SelectProfileForm
    template_name = 'profile/delete-member.html'

    def form_valid(self, form):
        profile = Profile.objects.get(pk=self.kwargs['pk'])
        profile.delete()
        return super().form_valid(form)

form

class SelectProfileForm(forms.ModelForm):
    profiles = forms.ModelChoiceField(
        widget=forms.Select,
        queryset=Profile.objects.all(),
        # empty_label="----None----",
    )  # here you can filter for what choices you need


    class Meta:
        model = Profile
        fields = ()

I get this error:

"KeyError at /profile/select/" "pk"

How can I delete the chosen instance?

Should I make a selection view and then a delete view separately? If so how can I redirect with the correct pk instance?

Thanks in advance!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source