[Django]-Django CreateView filter foreign key in select field

5👍

✅

You can add a queryset to the ForeignKey field.

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['form'].fields['turma'].queryset = Turma.objects.filter(representante=self.request.user)    
    context['titulo'] = 'Cadastrar aviso'
    context['input'] = 'Adicionar'
    return context

4👍

You could create a ModelForm for that model.
And based on this answer you could override the forms __init__() method to alter the fields queryset.

class AvisoForm(forms.ModelForm):
    class Meta:
        model = Aviso
        fields = [
            'data_final', 'comentarios', 'ultima_modificacao', 'data_post',
            'turma', 'materia',
        ]

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)

        # restrict the queryset of 'Turma'
        self.fields['turma'].queryset = self.fields['turma'].queryset.filter(
            representante=user)

Then, in your view, replace the attribute fields with form_class:

class AvisoCreateView(LoginRequiredMixin, CreateView):
    ...
    form_class = AvisoForm
    ...

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs

Maybe you need to adjust a few things for your specific case.
Let us know if that solved it.

Leave a comment