How to show content in a select that depends on another select?

1

My question is the following one ... I have a select that is a foreign key, and at the same time it has another foreign key, and what I want to do is select a data of the first select and that the second select changes its content depending on the first select

My code

Models.py correspondence, are more data but I do not put them

 class corresp(models.Model):
     Secretaria=models.ForeignKey(secretarias, null=True, blank=False)
     Unidad=models.ForeignKey(unidad, null=True, blank=False)

Models.py of User

class secretarias(models.Model):
    nombre_secretaria=models.CharField(max_length=80)
    ubicacion=models.CharField(max_length=100)

    def __unicode__(self):
        return '{}'.format(self.nombre_secretaria)

class unidad(models.Model):
    nombre_unidad = models.CharField(max_length=120)
    Secretaria= models.ForeignKey(secretarias, null=True, blank=True)

File code views.py

 def corresp_crear(request):
    if request.method == 'POST':
            form = CorrespondenciaForm(request.POST or None, request.FILES or None)
            if form.is_valid():
                 c = form.save(commit=False)
                 c.user = request.user
                 c.save()
                 messages.success(request, 'Correspondencia creada correctamente .')
              return redirect('correspondencia:corresp_listar')
      else:
            form = CorrespondenciaForm()
      return render(request, 'registrarCorrespondencia/formulario1.html', {'form': form})

Part of the file code formulario1.html

   <div class="well" style="overflow: auto">
     <label>Destino por Areas</label><br>
       <div class="col-md-6">{{ form.Secretaria.label}} {{ form.Secretaria}}</div>
       <div class="col-md-6">  {{ form.Unidad.label}} {{ form.Unidad}}</div>          
   </div>
    
asked by Lun 17.08.2018 в 00:31
source

1 answer

2

As it appears in the links that Tengito123 puts you, one of the most "pure" options would be to pull jQuery to do the chaining of the selects by hand.

I generally prefer to use for the django-autocomplete-light selects that already has a functionality to chain the selects in a very simple way and that also gives you the functionality of autocomplete.

Here I give you an example of some of the important code pieces, so you can see how it would look:

# forms.py

from dal import autocomplete

class CorrespondenciaForm(forms.ModelForm):

    class Meta:
        model = models.Correspondencia
        fields = ['unidad', 'secretaria', ]
        widgets = {
            'unidad': autocomplete.ModelSelect2(url='unidad-autocomplete')
            'secretaria': autocomplete.ModelSelect2(url='secretaria-autocomplete', 
                                                    forward=['unidad', ])
        }
        ... 



# views.py

class SecretariaAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):
        qs = models.Secretaria.objects.all()
        unidad = self.forwarded.get('unidad', None)
        if self.unidad:
            qs = qs.filter(unidad=unidad)

        if self.q:
            qs = qs.filter(nombre_secretaria__icontains=self.q)

        return results

I think this is a very clean and very easy way to get what you are consulting.

    
answered by 17.08.2018 в 12:34