如何使用模型对象数据填写表单?
我想用模型实例的数据填写表单。但我的表单的字段比模型少。如果我有这样的代码:
class Item(models.Model)
name = models.CharField(max_length=100)
price = models.PositiveIntegerField()
class ItemForm(forms.Form):
name = forms.CharField()
这个函数有什么问题以及它应该看起来如何才好?
def bound_form(request, id):
item = Item.objects.get(id=id)
form = ItemForm(item.name)
return render_to_response('bounded_form.html', {'form': form})
我收到这样的错误: AttributeError: 'ItemForm' object has no attribute 'get'
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'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通常,在为模型创建表单时,您需要使用 ModelForm。它遵循 DRY 原则,因此您不必重新定义表单类的字段类型。它还自动处理验证。您保留充分的灵活性来自定义所使用的字段和小部件。使用
fields
指定您想要的字段,或使用exclude
指定要忽略的字段。以您的示例为例:get_object_or_404()
在这里作为错误处理的一种形式很有用。否则,在丢失的 ID 上使用Item.objects.get(id=id)
将引发未捕获的Item.DoesNotExist
异常。当然,您也可以使用 try/ except 块。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 orexclude
to specify fields to ignore. With your example:get_object_or_404()
is useful here as a form of error handling. UsingItem.objects.get(id=id)
on a missing ID will throw an uncaughtItem.DoesNotExist
exception otherwise. You could use a try/except block also of course.