How can I fill up form with model object data?

krzyhub picture krzyhub · Aug 19, 2011 · Viewed 31.6k times · Source

I want to fill up form with data from model instance. But my form has less fields than model. If I have code like this:

class Item(models.Model)
    name = models.CharField(max_length=100)
    price = models.PositiveIntegerField()

class ItemForm(forms.Form):
    name = forms.CharField()

What wrong is with this function and how it should look to be good?

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

I getting error like this: AttributeError: 'ItemForm' object has no attribute 'get'

Answer

JCotton picture JCotton · Sep 21, 2011

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.