I’m trying to let my users edit a form they have previously created. All my form fields are being populated with their existing values with one exception. I have a ModelChoiceField that I’m unable to populate, it always shows the none value (“Select Client”). So my question is, how to I get this field populated when editing a form?
class WeeklyTime(models.Model):
SAVED = 'Saved'
PENDING = 'Pending'
APPROVED = 'Approved'
REJECTED = 'Rejected'
PUSHBACK = 'Pushed Back'
SUBMIT_STATUS_CHOICES = (
(SAVED, 'Saved'),
(PENDING, 'Pending'),
(APPROVED, 'Approved'),
(REJECTED, 'Rejected'),
(PUSHBACK, 'Pushed Back'),
)
username = models.ForeignKey(User, blank=False, null=False)
consultant = models.CharField(max_length=255)
client = models.CharField(max_length=255)
time_period = models.CharField(max_length=25)
class WeeklyTimeForm(ModelForm):
client = forms.ModelChoiceField(queryset=Clients.objects.all(), empty_label="(Select Client)")
#time_period = forms.DateField(widget=AdminDateWidget())
class Meta:
model = WeeklyTime
fields = ['consultant', 'client', 'time_period', 'mon_hours', 'tues_hours', 'wed_hours', 'thur_hours', 'fri_hours', 'sat_hours', 'sun_hours', 'total_hours', 'comments']
@login_required
def timeedit(request, slug):
activate(settings.TIME_ZONE)
#get the time detail
week = WeeklyTime.objects.get(slug=slug)
#set the form
form_class = WeeklyTimeForm`
#if coming from submitted timesheet
if request.method == 'POST':
#get the data
form = form_class(data=request.POST, instance=week)
if(form.is_valid()):
#
save the data
form.save()
messages.success(request, 'Your timesheet was updated successfully.')
return redirect('time_detail', slug=week.slug)
else:
messages.error(request, 'Your timesheet was not updated, please try again.')
return redirect('time_detail', slug=week.slug)
#otherwise create the form
else:
print("client="+str(week.client))
form = form_class(instance=week)
#render the template
return render(request, 'timeviews/week_edit.html', {'week': week, 'form': form,})