[Django]-How can I fill up form with model object data?

52👍

def bound_form(request, id): 
    item = Item.objects.get(id=id) 
    form = ItemForm(initial={'name': item.name}) 
    return render_to_response('bounded_form.html', {'form': form}) 

76👍

Generally when creating a form for a Model, you will want to use ModelForm. It keeps to the DRY principle such that you do not have to redefine field types for the form class. It also automatically handles validation. You retain full flexibility to customize the fields and widgets used. Use fields to specify the fields you want or exclude to specify fields to ignore. With your example:

from django import forms
from django.shortcuts import get_object_or_404

class ItemForm(forms.ModelForm):
    class Meta:
        model = Item
        fields = ("name", )

def bound_form(request, id):
    item = get_object_or_404(Item, id=id)
    form = ItemForm(instance=item)
    return render_to_response('bounded_form.html', {'form': form})

get_object_or_404() is useful here as a form of error handling. Using Item.objects.get(id=id) on a missing ID will throw an uncaught Item.DoesNotExist exception otherwise. You could use a try/except block also of course.

Leave a comment