Home > front end >  Django - ModelForm - Filter by user
Django - ModelForm - Filter by user

Time:06-29

I need to filter in EmployeeForm just to show me options of Companies related to user is logged in. I'm using ModelForm and CreateViews

This is my code:

models.py:

class Company(models.Model):
    reg_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    name = models.CharField(max_length=255)
    cuit = models.CharField(max_length=20)

class Employee(models.Model):
    company = models.ForeignKey(Empresa, on_delete=models.CASCADE)
    name = models.CharField(max_length=255)
    cuil = models.CharField(max_length=20)

forms.py:

class EmployeeForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        ...
        self.fields['name'].widget.attrs['autofocus'] = True

What is the code I need to write in the ellipses? It's currently showing me all companies even ones not owned by the user.

CodePudding user response:

I use forms.Form for this instead of ModelForm, but what i do is:

class EmployeeForm(forms.Form):
    companies = forms.ModelChoiceField(queryset=None)

    def __init__(self, user, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['companies'].queryset = Company.objects.filter(reg_user=user)

CodePudding user response:

I finally could solve this by using this in views.py

def get_form(self):
        form = super(EmployeeCreateView, self).get_form()
        form.fields['company'].queryset = Company.objects.filter(reg_user=self.request.user)
        return form

Thanks for everyone!

  • Related