Populate form field from ModelChoiceField with previously selected value


#1

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?

models.py

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)

forms.py

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']

views.py

@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,})

#2

Hey there! First off, looks like some of the code formatting in your message is off — can you edit your message to fix it or put the code on pastebin.com?

Also, can you clarify your issue — is the dropdown form not populating at all (and just has that one default value), or is the form populating but the initial value isn’t being set?

:)


#3

Tracy,
I attempted to reformat but it did not look great, so here is a pastebin https://pastebin.com/3ACrHYpW

My issue - the dropdown is populating with the values but it should have a selected value, say the second in the list, however it is showing “(Select Client)” indicating that the form is receiving None. However in my views.py I put a print statement (print(“client=”+str(week.client))) and it shows the correct value as a string.

Any ideas? (thanks in advance for your help!)


#4

I think this is happening because you’re using the modelfield so it’ll set the saved values:

class WeeklyTimeForm(ModelForm):

but then you’re defining an additional form field and it’s using the default field for that:

client = forms.ModelChoiceField(queryset=Clients.objects.all(), empty_label="(Select Client)")

Maybe this StackOverflow post will help? http://stackoverflow.com/questions/1336900/django-modelchoicefield-and-initial-value


#5

I wanted to follow up with what I’ve decided to be my solution to this issue. I was never able to get the drop down menu populated with the correct value, but I was getting the text value from the actual record. At the end of the day this is an edit form and I really don’t want my users changing the client’s name on the form, if they have made that large of an error they should delete and start over. Therefore I decided to just make the field disabled, it displays the client’s name and that is what I wanted the whole time.

client = forms.CharField(disabled=True)

#6

Sounds like a good solution, thanks for the update!