Praveen Singh Yadav
Praveen Singh Yadav

Reputation: 1861

Selected value of ChoiceField created by ForeignKey is not displayed in form

Background

I have a model

class Contact(models.Model):
       permanent_state      = models.ForeignKey(State)

in form.py

class ContactForm(forms.ModelForm):
    class Meta:
        model = Contact

in view.py

main(request):
     contact = Contact.objects.values().get(employee_id = emp) 
     print contact
     form  = ContactForm(initial = contact)
     print form
     return render(request,"dashboard/main.html",{  'form' : form})

problem: the form generates a drop down select html tag of permanent_state but does not show the state.instead it shows "------"

print output:

{ 'permanent_state_id': 2}



<tr><th><label for="id_permanent_state">Permanent state:</label></th><td><select id="id_permanent_state" name="permanent_state">
<option value="" selected="selected">---------</option>
<option value="1">Bengal</option>
<option value="2">Uttar Pradesh</option>
<option value="3">Tripura</option>
<option value="4">Tamil Nadu</option>
<option value="5">Sikkim</option>

But if I print the dict contact it gives me permanent_state value as 2. The selected value is correct in django admin app showing Uttar Pradesh

Please Help

Upvotes: 1

Views: 1143

Answers (1)

karthikr
karthikr

Reputation: 99620

Try this instead:

contact = Contact.objects.get(employee_id = emp) 
#Note that get throws an error if get() does not return a single value

form  = ContactForm(instance = contact)

Relevant documentation here

Upvotes: 2

Related Questions