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

Raf*_*sso 3 django django-views

我需要一些有关 Django 2 和 Python 3 的帮助。

\n\n

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

\n\n

这是我的模型:

\n\n
class Turma(models.Model):\n    nome                    = models.CharField(max_length=120, blank=False, null=False, help_text=\'Obrigat\xc3\xb3rio.\')\n    alunos                  = models.ManyToManyField(User, help_text=\'Obrigat\xc3\xb3rio\', related_name=\'alunos_matriculados\')\n    data_cadastro           = models.DateField(auto_now_add=True)\n    representante           = models.ForeignKey(User, on_delete=models.PROTECT, blank=False, null=False)\n    colegio                 = models.ForeignKey(Colegio, on_delete=models.PROTECT, blank=False, null=False, help_text=\'Obrigat\xc3\xb3rio.\')\n\nclass Aviso(models.Model):\n    data_final              = models.DateField(auto_now=False, auto_now_add=False, blank=False, null=False, verbose_name="Data Final")\n    comentarios             = models.TextField(null=True, blank=True)\n    ultima_modificacao      = models.DateField(auto_now=True)\n    data_post               = models.DateField(auto_now_add=True)\n    turma                   = models.ForeignKey(Turma, on_delete=models.PROTECT, null=False, blank=False)\n    materia                 = models.ForeignKey(Materia, on_delete=models.PROTECT, null=False, blank=False)\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是我的观点:

\n\n
class AvisoCreateView(LoginRequiredMixin, CreateView):  #Cadastro de Aviso\n    template_name = \'form.html\'\n    model = models.Aviso\n    login_url = \'/login/\'\n    success_url = reverse_lazy(\'visualizar_aviso\')\n    fields = [\n        \'turma\',\n        \'materia\',\n        \'tipo_aviso\',\n        \'comentarios\',\n        \'data_final\'\n    ]\n    def get_context_data(self, **kwargs):\n        context = super().get_context_data(**kwargs)\n\n        context[\'titulo\'] = \'Cadastrar aviso\'\n        context[\'input\'] = \'Adicionar\'\n        return context\n
Run Code Online (Sandbox Code Playgroud)\n\n

怎么可能呢?

\n

yan*_*zhi 5

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

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
Run Code Online (Sandbox Code Playgroud)