I'm making a project in which I need to implement a chained dropdown, the users select first their state, then their County, and then their Neighborhood, I've been looking into a lot of options and all of them are for either only two selects (like country then city), or for a function based view, and replicating this code in my class based view it isn't working. I'd very much appreciate any help. I'm new to Django.
Here are my models for location.models.py:
class Estado(models.Model):
estado = models.CharField(max_length=100)
def __str__(self):
return self.estado
class Municipio(models.Model):
municipio = models.CharField(max_length=100)
estado = models.ForeignKey(Estado, on_delete=models.CASCADE)
def __str__(self):
return self.municipio
class CP(models.Model):
cp = models.CharField(max_length=100)
municipio = models.ForeignKey(Municipio, on_delete=models.CASCADE)
estado = models.ForeignKey(Estado, on_delete=models.CASCADE)
def __str__(self):
return self.cp
class Colonia(models.Model):
colonia = models.CharField(max_length=100)
cp = models.ForeignKey(CP, on_delete=models.CASCADE)
municipio = models.ForeignKey(Municipio, on_delete=models.CASCADE)
estado = models.ForeignKey(Estado, on_delete=models.CASCADE)
def __str__(self):
return self.colonia
As for where I want to implement it, is in the Posts model, here are all the relevant codes, I think:
models.py
class PostRoom(models.Model):
author = models.ForeignKey(User,on_delete=models.CASCADE,default=1,related_name='room_author')
colonia = models.ForeignKey(Colonia, on_delete=models.SET_NULL, blank=False, null=True)
cp = models.ForeignKey(CP, on_delete=models.SET_NULL, blank=True, null=True)
municipio = models.ForeignKey(Municipio, on_delete=models.SET_NULL, blank=False, null=True)
estado = models.ForeignKey(Estado, on_delete=models.SET_NULL, blank=False, null=True)
views.py:
class RoomSubmitCreateView(LoginRequiredMixin, CreateView):
model = PostRoom
form_class = PostRoomForm
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
success_url = reverse_lazy('room_list')
How I want to adapt it in the template:
<div class="form-row">
<select class="custom-select col-12 col-md-4" name="category_name">
<option value="">Estado</option>
</select>
<select class="custom-select col-12 col-md-4" name="category_name">
<option value="">Municipio</option>
</select>
<select class="custom-select col-12 col-md-4" name="category_name">
<option value="">Colonia</option>
</select>
</div>
Thank you all and Happy New Year!!