Lucas Rezende
Lucas Rezende

Reputation: 2686

Auto Fill ModelForm with data already stored in database

I got a form as shown below and I want it to be filled with information from the database when its HTML is rendered. I am passing the id of the Coworker as a parameter for the view.

See code below:

view.py

def EditCoworker(request, id):
    form = FormEditCoworker(Coworkers.objects.get(id=id))
    if request.method == "POST":
        form = FormEditCoworker(request.POST)
        if form.is_valid():
            form.save()
            confirmation_message = "Coworker information updated successfully!"
            return render(request, "coworkers/coworkers.html", locals())
        else:
            return render(request, "coworkers/edit_coworker.html", locals())
    return render(request, 'coworkers/edit_coworker.html', locals())

forms.py

class FormEditCoworker(ModelForm):
    class Meta:
        model = Coworkers

urls.py

url(r'^edit_coworker/(?P<id>[\d]+)$', views.EditCoworker),

Of course the code in my views.py is not right.

Can someone help me on this?

Thanks in advance!

Upvotes: 4

Views: 3154

Answers (1)

Iain Shelvington
Iain Shelvington

Reputation: 32294

This line

form = FormEditCoworker(Coworkers.objects.get(id=id))

Should be

form = FormEditCoworker(instance=Coworkers.objects.get(id=id))

Although you should really handle the case where the Coworker doesn't exist

form = FormEditCoworker(instance=get_object_or_404(Coworkers, id=id))

EDIT: As Alisdair said, you should also pass the instance keyword arg to the bound form also

instance = get_object_or_404(Coworkers, id=id)
form = FormEditCoworker(instance=instance)
if request.method == "POST":
    form = FormEditCoworker(request.POST, instance=instance)

Upvotes: 4

Related Questions