Initially posted on stack overflow:

https://stackoverflow.com/questions/59395761/passing-dynamic-choices-into-a-formset-unique-for-each-form

I am working on what I thought was a simple college football confidence 
pool. The concept is as follows:

   - Bowl Model: Model that stores information of each bowl game being 
   played this season
   - Team Model: Model for all the teams playing in a bowl with a foreign 
   key to the bowl

models.py

    from django.db import models
    from django.contrib.auth.models import Group, User

    class Bowl(models.Model):
        """Model for Bowl Game information"""
        name = models.CharField(max_length=200)
        b_date = models.DateField(null=True, blank=True)
        b_time = models.TimeField(null=True, blank=True)
        tv = models.CharField(max_length=10)
        location = models.CharField(max_length=200)

        def __str__(self):
            """String for representing the bowl object"""
            return self.name

    class Team(models.Model):
        name = models.CharField(max_length=200)
        bowl = models.ForeignKey(Bowl,on_delete=models.SET_NULL,null=True)

        def __str__(self):
            """String for representing the intermediate table"""
            return self.name   

I'm attempting to create a page has a formset which allows the user to pick 
the predicted winner of each game. Therefore I constructed the following 
view to call the form and formset.
views.py

   def fs_test(request):

       bowl_list = Bowl.objects.all()
       bowl_len = len(bowl_list)
       bowl_data = []

       TestFormSet = formset_factory(TestForm, extra=0)

       for bowl in bowl_list:
          bowl_data.append({
              't_bowl': bowl.name,'t_user':request.user,'t_weight':1,
              't_winner':winner_data,
          })

       if request.method == 'POST':
           pass
       else:
           formset = TestFormSet(initial=bowl_data)

           context = {
               'formset':formset, 'bowl_data':bowl_data
           }
       return render(request, 'catalog/test_bowl.html',context)

The following form inherits pre-populated data via passing "bowl_data" in 
the "initial" parameter.
forms.py

    class TestForm(forms.Form):
         def __init__(self, *args, **kwargs):
         super(TestForm, self).__init__(*args, **kwargs)
         self.fields['t_bowl'] = forms.CharField()
         self.fields['t_weight'] = forms.IntegerField()
         self.fields['t_user'] = forms.CharField()
         self.fields['t_winner'] = forms.ChoiceField(
             widget=forms.RadioSelect,
             required=True,
             choices=[(o.name, o.name)
                 for o in Team.objects.filter(bowl__name__exact=self.t_bowl)]
         )

I believe pre-populating the t_winner choices are failing because using the 
self.t_bowl in the query is just a field reference not the name of the 
field. I don't know how to pass in the "bowl" name to the form query. Or 
maybe I pre-populate the "choices" in the view but I don't know how to pass 
a dict into it and reference the correct index.

I've done some reading on the get_form_kwargs, but I'm not clear on how to 
use it in this instance.

It's entirely possible I'm using the wrong data model for this task, 
however I've been stumped for a couple of day on this. It took me a while 
to even figure out how to pass in unique "initial" values for each form in 
the formset.

Any recommendations would save what little hair I have left. Thank you!



-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/0f19f3ef-7c5d-409c-98ab-150c07a196e1%40googlegroups.com.

Reply via email to