[Answered ]-Limit the Choices shown from ManyToMany ForeignKey

1👍

As I mentioned above, Dean’s answer was really close, but didn’t work for me. Primarily because request is not accessible in the view directly. Maybe it is in older Django versions? I’m on 1.9. Thank you Dean, you got me over the hump!

The gist of what’s going on is adding User into the kwargs in the View, passing that to the ModelForm, remove User from the kwargs and use it to filter the Spots before the form is shown.

This is the code that worked for my project:

views.py

class ProjectUpdate(UpdateView):
    model = Project
    success_url = reverse_lazy('projects-mine')
    form_class = ProjectForm

def dispatch(self, *args, **kwargs):
    return super(ProjectUpdate, self).dispatch(*args, **kwargs)

def get_form_kwargs(self):
    kwargs = super(ProjectUpdate, self).get_form_kwargs()
    kwargs.update({'user': self.request.user})
    return kwargs

forms.py

class ProjectForm(forms.ModelForm):
    class Meta:
        model = Project
        exclude = ('owner', 'whispir_id')

    def __init__(self, *args, **kwargs):
        user_id = kwargs.pop('user')
        super(ProjectForm, self).__init__(*args, **kwargs)
        self.fields['spots'] = forms.ModelMultipleChoiceField(queryset=Spot.objects.filter(owner=user_id))


class SpotForm(forms.ModelForm):
    class Meta:
        model = Spot
        exclude = ('owner', )

    def __init__(self, *args, **kwargs):
        user_id = kwargs.pop('user')
        super(SpotForm, self).__init__(*args, **kwargs)
        self.fields['spot_name'] = forms.ModelMultipleChoiceField(queryset=Spot.objects.filter(owner=user_id))

1👍

in your forms.py

class ProjectForm(forms.ModelForm):
    class Meta:
        model = Project
        exclude = ('owner', )

    def __init__(self, user_id, *args, **kwargs):
        self.fields['spots'] = forms.ModelChoiceField(widget=forms.Select, queryset=Project.objects.filter(owner=user_id))


class SpotForm(forms.ModelForm):
    class Meta:
        model = Spot
        exclude = ('owner', )

    def __init__(self, user_id, *args, **kwargs):
        self.fields['spot_name'] = forms.ModelChoiceField(widget=forms.Select, queryset=Spot.objects.filter(owner=user_id))

in your views.py

user_id = Project.objects.get(owner=request.user).owner
project_form = ProjectForm(user_id)
spot_form = SpotForm(user_id)

Leave a comment