Django ModelForm filter according to another field

0

I am trying to make the drop-down list of a field change according to what you have selected in another field, in my case it changes the state according to the selected municipality, that is to say that only the states corresponding to that municipality come out

Models.py

class Temporal(models.Model):
    a000sap = models.CharField(max_length=25)
    codigo_unico = models.CharField(max_length=25)
    visitas = models.IntegerField()
    latitud = models.FloatField()
    longitud = models.FloatField()
    direccion_fisica = models.CharField(max_length=2000)
    direccion_fiscal = models.CharField(max_length=2000)
    persona_contacto = models.CharField(max_length=70)
    municipio_key = models.ForeignKey(Municipios, 
    on_delete=models.CASCADE,null=True)
    estado_key =models.ForeignKey(Estados,on_delete=models.CASCADE,null=True)


class Ciudades(models.Model):
    id_ciudad = models.AutoField(primary_key=True)
    id_estado = models.ForeignKey(Estados, db_column='id_estado')
    ciudad = models.CharField(max_length=200)
    capital = models.SmallIntegerField()
    def __str__(self):
        return str(self.ciudad, self.capital)

class Municipios(models.Model):
    id_municipio = models.AutoField(primary_key=True)
    id_estado = models.ForeignKey(Estados, db_column='id_estado')
    municipio = models.CharField(max_length=100)
    def __str__(self):
        return self.municipio

Forms.py

class editar(ModelForm):
    def __init__(self, *args, **kwargs):
        super(editar, self).__init__(*args,**kwargs)
        self.fields['estado'].queryset = Municipios.objects.filter(municipio__iexact=(VARIABLE CON MUNICIPIO QUE ELIGIO EL USER)
        for f in self.fields.items():
            if (f[0] in meses) or (f[0] == 'punto_rojo'):
                continue
            else:
                self.fields[f[0]].widget.attrs["class"] = 'form-control'
        self.fields['codigo_unico'].widget.attrs["readonly"] = True
    class Meta:
        model = Temporal
        fields = '__all__'

I do not know how to get the value of the municipality field to insert it in the queryset

    
asked by Anthony 04.05.2018 в 16:58
source

1 answer

0

Somehow you have to collect the data to be able to process the information in the view, the ideal is to pass it by means of "get" for example:

class Editar(forms.ModelForm):
    model = Temporal
    fields = '__all__'

    def __init__(self, *args, **kwargs):
        state = kwargs.pop('departament')
        super(editar, self).__init__(*args,**kwargs)
        cities_by_state = Municipios.objects.filter(municipio__iexact=state)
        self.fields['estado'].queryset =cities_by_state
        for f in self.fields.items():
            if (f[0] in meses) or (f[0] == 'punto_rojo'):
                continue
            else:
                self.fields[f[0]].widget.attrs["class"] = 'form-control'
        self.fields['codigo_unico'].widget.attrs["readonly"] = True


class EditarFormView(FormView):

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['state'] = self.request.GET.get('state')
        return kwargs
    
answered by 05.05.2018 в 03:15