【问题标题】:Django init función define field choices based on URL pkDjango init 函数根据 URL pk 定义字段选择
【发布时间】:2020-09-27 14:08:34
【问题描述】:

我有一个工作表单集。

我的目标是根据在 url 上发送的 pk 定义来自其他模型的字段选择。它几乎可以工作了,但是 init 方法被执行了两次并清理了 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】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2020-09-28
      • 2018-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-23
      • 2013-12-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多