kikee1222
kikee1222

Reputation: 2036

filtering modelchoicefield by currently logged in user

I have the below modelchoicefield with the values of the dropdown populated by a model query. I want to add a filter too, where the logged in user = the username in the model field (called user),

I can't seem to get it working, can you please help?

forms.py

class UploadFileForm(forms.Form):
    title = forms.ModelChoiceField(queryset=projects.objects.filter(user=user).values_list('project_name', flat=True).distinct())
    file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))

views.py

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES, user=request.user)
        zz = 0
        x = request.POST.get('title')

Upvotes: 0

Views: 400

Answers (1)

schillingt
schillingt

Reputation: 13731

You can modify the queryset of the field after you initialize the form. Here's one way to do it:

class UploadFileForm(forms.Form):
    title = forms.ModelChoiceField(queryset=projects.objects.values_list('project_name', flat=True).distinct())
    file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))

    def __init__(*args, user, **kwargs):
        super().__init__(*args, **kwargs)
        self.title.queryset = self.title.queryset.filter(user=user)

Upvotes: 1

Related Questions