Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

django - How can I fill up form with model object data?

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'

question from:https://stackoverflow.com/questions/7122071/how-can-i-fill-up-form-with-model-object-data

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...