[Fixed]-Prepopulate 1 form field that is a foreign key

1👍

You haven’t defined an init method for this code to go into, thusly its just reading each line individually as a declaration

Move your code into an init method and it should work fine!

class LimitedJobForm(forms.ModelForm):

    jobnum = forms.CharField(label='Job Number')
    color = forms.CharField()

    def __init__(self, *args, **kwargs):
        super(LimitedJobForm, self).__init__(*args, **kwargs)
        cur_jobs = Job.objects.filter(enddate__gte=(datetime.date.today()-timedelta(days=7)))
        all_colors = Color.objects.all()
        cur_colors = []
        for i in cur_jobs:
            cur_colors.append(i.color)
        aval_colors = [x for x in all_colors if x not in cur_colors]
        choice = random.choice(aval_colors)
        self.fields['color'].initial = choice
👤Sayse

Leave a comment