ellieinphilly
ellieinphilly

Reputation: 477

Django Dynamic Form Choices from ManyToMany Field

I'm trying to build a form that displays dynamic choices

How do I build a Form where the athlete's Sport is a choicefield populated with sports related to the Event that the athlete is participating in...

my models are as follows...

class Sport(models.Model):
    Type = models.CharField(max_length=15)

class EventCode(models.Model):
    Description = models.CharField(max_length=95)
    Sports = models.ManyToManyField(Sport)

class Athlete(models.Model):
    Event = models.ForeignKey(EventCode)
    Sport = models.ForeignKey(Sport)

Upvotes: 1

Views: 2881

Answers (1)

Pannu
Pannu

Reputation: 2657

I assume you know the event code when you are building the form This is the way you filter on the EventCode:

sport_choices = EventCode.objects.filter(pk=event).values_list('Sports','Sports__Type')

lets say the event is jump then you will get [(5,'long jump'),(7,'frog jump')....]

Now the way you set the related choices is

Class AthleteForm(ModelForm):
      class Meta:
            model = Athlete
      def __init__(self,*args, **kwargs):
          super(AthleteForm, self).__init__(*args, **kwargs)
          event = kwargs['event']
          self.fields['Event'].initial = event
          self.fields['Sport'].choices =  EventCode.objects.filter(pk=event).values_list('Sports','Sports__Type')

If you want to do this when you select an event in the form then you can pass the event as ajax request generate the sport_choices for the selected event and return it as a response to the ajax request.

Upvotes: 5

Related Questions