MattG
MattG

Reputation: 1932

How to filter Django's foreignKey form dropdown

I have a form that is used to edit (update) a record, and the Author field is automatically a dropdown, which is great, but how do you filter this list? For example, the dropdown is populated with the entire user list. How can I filter this list so that it only shows the items where isDevice == True?

accounts/models.py

from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
    isDevice = models.BooleanField(default = False)
    ...

builds/models.py

class BuildQueue(models.Model):
    Author =  models.ForeignKey(CustomUser,blank=True, null= True, on_delete=models.CASCADE)
    ...

forms.py

class BuildQueueEditForm(forms.ModelForm):
    class Meta:
        model = BuildQueue
        fields = ['Author','project', 'customer',]

views.py

class buildQueueEdit(LoginRequiredMixin,UpdateView):
    model = BuildQueue
    form_class = BuildQueueEditForm
    template_name = 'buildQueue_edit.html'

Upvotes: 2

Views: 651

Answers (1)

mrEvgenX
mrEvgenX

Reputation: 766

Since UpdateView inherited also from FormMixin, in your buildQueueEdit you can override get_form, where form is instantiated and exactly where you can modify the form's field's queryset.

class buildQueueEdit(LoginRequiredMixin,UpdateView):
    model = BuildQueue
    form_class = BuildQueueEditForm
    template_name = 'buildQueue_edit.html'

    def get_form(self, form_class=None):
        form = super().get_form(form_class)
        form.fields['Author'].queryset = CustomUser.objects.filter(isDevice=True)
        return form

UPDATE

If you want to change text displayed in your dropdown you can override choises instead of queryset. It worked for me.

form.fields['Author'].choices = [(item.id, item.equipmentName) for item in CustomUser.objects.filter(isDevice=True)]

Upvotes: 3

Related Questions