Populate a select dropdown based on queryset

30 views
Skip to first unread message

James Farris

unread,
Mar 28, 2018, 5:02:36 PM3/28/18
to Django users
Hi,

I'm trying to populate a 'vaccine' dropdown based on a 'species' of a pet.  For example, if a pet is a 'dog' I want to display vaccines for a dog only.  If a pet is a cat, I want to display a list of vaccines for cats only.

How do I do this?  I googled, but didn't come up with anything solid.

Here is my models.py

class Pet(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
name = models.CharField(max_length=100, null=True, db_index=True)
species = models.CharField(choices=SPECIES_CHOICES, null=True, max_length=20)

def __str__(self):
return self.name


class Vaccine(models.Model):
vacc_name = models.CharField(max_length=100)
species = models.CharField(choices=SPECIES_CHOICES, null=True, max_length=20)
pet = models.ManyToManyField(Pet, through='PetHasVaccine')

def __str__(self):
return self.vacc_name


class PetHasVaccine(models.Model):
pet = models.ForeignKey(Pet, on_delete=models.DO_NOTHING)
vaccine = models.ForeignKey(Vaccine, on_delete=models.DO_NOTHING)

def __str__(self):
return str(self.pet.name) + ' - ' + str(self.vaccine.vacc_name)


Here is my views.py

def add_vaccine(request, pet_pk):
pet = Pet.objects.get(pk=pet_pk)
if pet.user == request.user:
form = VaccineForm(request.POST or None)
if request.POST:
if form.is_valid():
return HttpResponse(form)
else:
return render(request, 'pet/vaccine_add.html', {'vacc_form': VaccineForm(request.POST), 'pet': pet})
else:
return render(request, 'pet/vaccine_add.html', {'vacc_form': form, 'pet': pet})


Here is my forms.py

class VaccineForm(ModelForm):

class Meta:
model = PetHasVaccine
fields = '__all__'
exclude = ('pet',)
widgets = {
'date_given': DateInput(),
'date_due': DateInput(),
}

Derek

unread,
Mar 30, 2018, 3:08:07 AM3/30/18
to Django users
You can use "smart selects":


Works for both normal forms and in the admin.

James Farris

unread,
Mar 30, 2018, 9:10:39 PM3/30/18
to django...@googlegroups.com
Thank you Derek! I will definitely look into it. 

-James
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/172ae5f3-df10-4bf2-acdc-390dea7edc49%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages