Reputation: 836
Previously I was letting the user pick from a drop down of colors but I would like to rather pick one for them so I used the following code to determine which colors would be a valid choice and then randomly chose one. I'm trying to get it to pre-populate in the form and I'm getting a name error. Scratching my head like crazy because I tested this code by simply piping choice
into a template already. So I know the code functioned properly in that context. Can I not do something that I've done below?
The error I'm getting when I launch my server is Name Error: name 'cur_colors' [at the list comprehension line] is not defined
but it clearly is...
class LimitedJobForm(forms.ModelForm):
jobnum = forms.CharField(label='Job Number')
#get colorchoice
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)
color = forms.CharField(initial=choice)
Upvotes: 0
Views: 494
Reputation: 43300
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
Upvotes: 1