[Answer]-Set default value for dynamic choice field

0👍

I got it to work after playing around for a while. Above, I was setting all the dynamic choices with a get_dates() function that returned a tuple. Instead of doing that I returned a field object like this using a customized ModelChoiceField instead of a regular ChoiceField….

class MyModelChoiceField(ModelChoiceField):

    def label_from_instance(self, obj):
        return obj.date.strftime('%a %b %d, %Y')

Dates function

def get_dates(self,zip):        
            routes = Route.objects.filter(zip=zip).values_list('route',flat=True)
            pickups = self.MyModelChoiceField(queryset = PickupSchedule.objects.filter(         
                    current_count__lt=F('specials'),
                    route__in=routes,
                ).order_by('date')
            )    

            if not pickups:
                pickups = (('----','No Pickups Available At This Time'),)

            return pickups

in the init i set the value for self.fields['pickup_date'] like so..

self.fields['pickup_date'] = self.get_dates(zip)
👤Austin

1👍

Change self.fields[‘pickup_date’] to self.fields[‘pickup_date’].initial and see if that helps.

Leave a comment