我对Django对象模型感到有些困惑。我有这样的模型:
# Create your models here.
class Item(models.Model):
code = models.CharField(max_length=200, unique=True)
barcode = models.CharField(max_length=300)
desc = models.CharField('Description',max_length=500)
reg_date = models.DateField('registered date')
registrar = models.CharField(max_length=100)
def __unicode__(self):
return self.code + ' : ' + self.desc
class ItemInfo(models.Model):
item = models.OneToOneField(Item, primary_key=True)
supplier = models.ForeignKey(Supplier)
stock_on_hand = models.IntegerField()
stock_on_order = models.IntegerField()
cost = models.IntegerField()
price = models.IntegerField()
unit = models.CharField(max_length=100)
lead_time = models.IntegerField()
但是当我尝试将Item和ItemInfo检索到模型中时,我收到了以下错误:
'ModelFormOptions' object has no attribute 'many_to_many'
。我怀疑这一行supplier = models.ForeignKey(Supplier)
有问题。有人可以解释我何时使用ForeignKey
或关系字段(OneToOneFields, ManyToManyFields, ManyToOneFields)
编辑:ModelForm:
class ItemForm(ModelForm):
class Meta:
model = Item
widgets = {
'registrar' : TextInput(attrs={'ReadOnly' : 'True'})
}
class ItemInfoForm(ModelForm):
class Meta:
model = ItemInfo
exclude = ('item')
这是我使用模型中的填充值生成表单的方法:
def details(request, code):
csrf_context = RequestContext(request)
current_user = User
if request.user.is_authenticated():
item = Item.objects.get(pk=code)
item_info = ItemInfo.objects.get(pk=item.pk)
item_form = ItemForm(instance=item)
item_info_form = ItemInfoForm(instance=item_form)
return render_to_response('item/details.html',
{'item_form' : item_form, 'item_info_form' : item_info_form},
csrf_context)
else:
return render_to_response('error/requires_login.html', csrf_context)
Traceback:
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "G:\tulip\stock\item\views.py" in details
131. item_info_form = ItemInfoForm(instance=item_form)
File "C:\Python27\lib\site-packages\django\forms\models.py" in __init__
237. object_data = model_to_dict(instance, opts.fields, opts.exclude)
File "C:\Python27\lib\site-packages\django\forms\models.py" in model_to_dict
112. for f in opts.fields + opts.many_to_many:
Exception Type: AttributeError at /item/details/1/
Exception Value: 'ModelFormOptions' object has no attribute 'many_to_many'
答案 0 :(得分:2)
您正在使用ItemInfoForm
实例实例化ItemForm
。虽然instance
应为ItemInfo
实例,但不是
正确的行:
item_info_form = ItemInfoForm(instance=item_info)