filter field set in django formds 1

filter field set in django formds

class AgregarProducto(forms.ModelForm):
    class Meta:
        model   = productos

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(AgregarProducto, self).__init__(*args, **kwargs)
        self.fields['secciones'].queryset = secciones.objects.filter(user=user)

Here is what the above code is Doing:
1. We’re creating a new class called AgregarProducto that inherits from forms.ModelForm.
2. We’re telling Django that the model we want to use for this form is the productos model.
3. We’re overriding the __init__ method of the form.
4. We’re getting the user from the kwargs.
5. We’re calling the __init__ method of the parent class (forms.ModelForm) and passing it the args and kwargs.
6. We’re filtering the secciones queryset to only include secciones that belong to the user.

Similar Posts