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.pyclass VaccineForm(ModelForm):
class Meta:
model = PetHasVaccine
fields = '__all__'
exclude = ('pet',)
widgets = {
'date_given': DateInput(),
'date_due': DateInput(),
}
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@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/0dd005ba-1d3a-4dd2-ab94-4d1f3b94f287%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
No comments:
Post a Comment