Reputation: 836
Initially I was populating my form with an initial value and disabling the field to let the user know that the option that has been randomly selected for this form. But I've run into a few issues and it just seems better to not even show this in my form to the user but notify them later with messages. Though I'm not quite sure how to do this. I need to assign a color to my job model on form submission for the job. I have:
This is what I use to pick what color to assign to each new job.
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)
These are my models:
class Job(models.Model):
---other stuff---
jobnum = models.CharField("Job Number",max_length=6, blank=False,unique=True,error_messages={'unique':'This Job Number is already taken! =)'})
color = models.ForeignKey('Color')
class Color(models.Model):
color = models.CharField(max_length=20, blank=False)
def natural_key(self):
return (self.color)
def __str__(self): #python 3.3. is __str__
return self.color
How can I take choice
and submit it as a color
with the jobform
instance?
Job form:
class LimitedJobForm(forms.ModelForm):
jobnum = forms.CharField(label='Job Number')
class Meta:
model = Job
fields = ['jobnum','color','client','status']
Upvotes: 3
Views: 342
Reputation: 17781
If you want color
to be automatically set, and if you don't even want it to be displayed to the user, do not put it in your form:
class LimitedJobForm(forms.ModelForm):
jobnum = forms.CharField(label='Job Number')
class Meta:
model = Job
fields = ['jobnum', 'client', 'status'] # no 'color' field
Instead, set the color directly on the model instance in your view, after validating the form and before saving it:
form = LimitedJobForm(request.POST)
if form.is_valid():
form.instance.color = pick_random_color()
form.save()
Upvotes: 2