How to filter foreignkey choices in a django modelform with Python?

Estimated read time 1 min read

To filter the choices for a ForeignKey field in a Django ModelForm, you can override the form’s __init__ method and modify the queryset of the field. Here’s an example:

from django import forms
from .models import MyModel

class MyModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Filter the choices for the foreign key field
        self.fields['foreign_key_field'].queryset = MyModel.objects.filter(some_condition=True)
    class Meta:
        model = MyModel
        fields = '__all__'

In the example above, we define a MyModelForm class that inherits from forms.ModelForm. In the __init__ method, we call the parent’s __init__ method to set up the form. Then, we access the foreign_key_field on self.fields and modify its queryset attribute.

In this case, we filter the queryset by some condition (some_condition=True) specific to your requirements. You can replace some_condition=True with the filtering logic that suits your needs.

Finally, we define the Meta class within the form, specifying the model MyModel and using '__all__' to include all fields from the model in the form.

Now, when you instantiate the MyModelForm, the choices for the foreign_key_field will be filtered based on the specified condition.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply