选择字段中的Django CreateView过滤器外键

时间:2018-07-04 19:55:44

标签: django django-views

我需要Django 2和Python 3的帮助。

我正在使用CreateView在数据库中添加新的记录,但是我需要为Aviso表单页面创建一个过滤器以创建选择字段(字段turma)仅显示representante是当前用户的实例。

这是我的模特

class Turma(models.Model):
    nome                    = models.CharField(max_length=120, blank=False, null=False, help_text='Obrigatório.')
    alunos                  = models.ManyToManyField(User, help_text='Obrigatório', related_name='alunos_matriculados')
    data_cadastro           = models.DateField(auto_now_add=True)
    representante           = models.ForeignKey(User, on_delete=models.PROTECT, blank=False, null=False)
    colegio                 = models.ForeignKey(Colegio, on_delete=models.PROTECT, blank=False, null=False, help_text='Obrigatório.')

class Aviso(models.Model):
    data_final              = models.DateField(auto_now=False, auto_now_add=False, blank=False, null=False, verbose_name="Data Final")
    comentarios             = models.TextField(null=True, blank=True)
    ultima_modificacao      = models.DateField(auto_now=True)
    data_post               = models.DateField(auto_now_add=True)
    turma                   = models.ForeignKey(Turma, on_delete=models.PROTECT, null=False, blank=False)
    materia                 = models.ForeignKey(Materia, on_delete=models.PROTECT, null=False, blank=False)

这是我的观点:

class AvisoCreateView(LoginRequiredMixin, CreateView):  #Cadastro de Aviso
    template_name = 'form.html'
    model = models.Aviso
    login_url = '/login/'
    success_url = reverse_lazy('visualizar_aviso')
    fields = [
        'turma',
        'materia',
        'tipo_aviso',
        'comentarios',
        'data_final'
    ]
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        context['titulo'] = 'Cadastrar aviso'
        context['input'] = 'Adicionar'
        return context

那怎么办?

2 个答案:

答案 0 :(得分:1)

您可以为该模型创建一个ModelForm。 并且基于this answer,您可以覆盖表单__init__()方法来更改字段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)

然后,在您看来,将属性fields替换为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

也许您需要针对特定​​情况调整一些内容。 让我们知道是否解决了这个问题。

答案 1 :(得分:0)

您可以将查询集添加到ForeignKey字段。

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