Django初始化函数根据URL pk定义字段选择

问题描述 投票:0回答:1

我有一个有效的表单集。

我的目标是根据url发送的pk定义其他模型的字段选择。几乎可以用了,但是init方法在twyce中执行并清除kwargs。

型号:

class Delito(models.Model):
    numero = models.ForeignKey(Expediente, on_delete=models.CASCADE,  blank = False)
    delito = models.ForeignKey(CatalogoDelitos, on_delete=models.CASCADE,  blank = False)
    imputado = models.ForeignKey(Imputado, on_delete=models.CASCADE,  blank = False)
    categoria = models.CharField('Categoria', max_length = 20, blank = False, choices = CATDEL_CHOICES)

我的网址:

path('crear_delito/<int:pk>',  login_required(CrearDelito.as_view()),  name ='crear_delito'),

Forms.py:

class CrearDelitoForm(forms.ModelForm):
    class Meta:
        model = Delito
        exclude = ()

    def __init__(self, numero_pk = None, *args, **kwargs):
        super(CrearDelitoForm, self).__init__(*args, **kwargs)
        self.fields["imputado"].queryset = Imputado.objects.filter(numero_id = numero_pk)

DelitoFormset = inlineformset_factory(
    Expediente,
    Delito,
    form=CrearDelitoForm,    
    extra=1,
    can_delete=True,
    fields=('imputado', 'delito', 'categoria'),
    } 
)

Views.py:

class CrearDelito(CreateView):
    model = Delito
    form_class = CrearDelitoForm
    template_name = 'crear_delito.html'

    def get_context_data(self,**kwargs):
        context = super().get_context_data(**kwargs)
        context['formset'] = DelitoFormset()        
        context['expedientes'] = Expediente.objects.filter(id = self.kwargs['pk'])
        return context

    def get_form_kwargs(self, **kwargs):
        kwargs['numero_pk'] = self.kwargs['pk']
        return kwargs

如果我打印查询集,它会在第一次运行,但会传递两次以清除“ numero_pk”值:

System check identified no issues (0 silenced).
June 08, 2020 - 11:33:57
Django version 2.2.12, using settings 'red.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
<QuerySet [<Imputado: Martín Ric>, <Imputado: Marcos Gomez>]>
<QuerySet []>

如果将值作为字符串放置,则可以正常工作,例如:

def __init__(self, numero_pk = None, *args, **kwargs):
   super(CrearDelitoForm, self).__init__(*args, **kwargs)
   self.fields["imputado"].queryset = Imputado.objects.filter(numero_id = '6')

enter image description here

django django-queryset init formset
1个回答
0
投票

我发布了其他问题中给出的解决方案:

class CrearDelito(CreateView):
model = Delito
form_class = CrearDelitoForm
template_name = 'crear_delito.html'

def get_context_data(self,**kwargs):
    context = super().get_context_data(**kwargs)
    context['formset'] = DelitoFormset()        
    context['expedientes'] = Expediente.objects.filter(id = self.kwargs['pk'])
    return context

def get_form_kwargs(self, **kwargs):
    kwargs['numero_pk'] = self.kwargs['pk']
    return kwargs here
© www.soinside.com 2019 - 2024. All rights reserved.