ReverseManyTone通过django表单从子对象创建对象
使用: Python 3.7.3 django 2.2.5 mysql 5.7.27 我有以下型号:ReverseManyTone通过django表单从子对象创建对象,django,python-3.x,foreign-keys,relationship,Django,Python 3.x,Foreign Keys,Relationship,使用: Python 3.7.3 django 2.2.5 mysql 5.7.27 我有以下型号: class Item(models.Model): ... class Comments(models.Model): Item = models.ForeignKey('Item', default=None, null=True, on_delete=models.CASCADE) Comment = models.TextField(max_length=512, def
class Item(models.Model):
...
class Comments(models.Model):
Item = models.ForeignKey('Item', default=None, null=True, on_delete=models.CASCADE)
Comment = models.TextField(max_length=512, default="", blank=True)
我想在通过django表单创建项目时创建一个Comments对象。我试着做:
class ItemInsertForm(forms.ModelForm):
...
Comments = forms.CharField(required=False,
widget=forms.Textarea(attrs={'placeholder':"Use comments to describe item details \
or issues that other users should know",
'rows':5,
'cols':50,
}
)
)
def clean_Comments(self, *args, **kwargs):
_comment = self.cleaned_data.get('Comments')
_comments = Item.comments_set.create(Comment=_comment)
return _comments
但我得到了以下错误:
“ReverseManyToOneDescriptor”对象没有属性“create”
两个表都为空,因此当前不存在任何项和注释。我想这就是为什么没有“创建”方法可用的原因。有什么方法可以实现我想要的吗
或者是否有其他方法来管理Item对象的注释?我创建了另一个表,以便能够将多个注释关联到同一项并区分它们。Item类中的字符字段将把所有注释连接在一个字符串中。我发现您的代码有很多问题,但我觉得您是诚实地尝试了一下,所以我会尽力帮助您 首先是models.py文件:
- 模型名称应为单数,因此使用
,而不是Comment
Comment
- 类成员应为小写,因此
和Item
应更改为Comment
和Item
Comment
仍然不是很有描述性。注释是实际对象,它的内容是注释中的文本,因此Comment.Comment
在这里更合适text
的外键已将默认值设置为无null=True
class Item(models.Model):
...
class Comment(models.Model):
item = models.ForeignKey(Item, null=True, on_delete=models.CASCADE)
text = models.TextField(max_length=512, default="", blank=True)
然后,转到您的表单:
comment = form.save()
comment.item = item.
comment.save()
- 由于它是用于创建
,因此更合适的名称应该是注释的表单
CommentForm
是为在def clean_Comments(self、*args、**kwargs):
字段上执行验证而保留的函数,不用于从表单输入创建对象。为此,您可以使用ModelForm的方法。不过,如果要执行某些自定义逻辑,则只需定义一个save方法Comments
class ItemInsertForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['text']
text = forms.CharField(required=False,
widget=forms.Textarea(attrs={'placeholder':"Write your comment to describe item details \
or issues that other users should know",
'rows':5,
'cols':50,
}
)
)
提交此表单时,将创建一个注释
对象。但是,仍然无法将注释添加到项目
为此,您需要确保数据库中存在
Item
实例,或者允许用户通过ItemForm
有多种方法可以做到这一点:
modelcooicefield
添加到CommentForm,这将允许用户从选择列表中选择项目item=item.objects.get(pk=)
comment=form.save()
项目注释集添加(注释)
item.save()
嘿,谢谢你抽出时间回答,你有一些好的观点。ItemInsertForm不是一个用于添加注释的表单,而是一个用于创建项目的表单,但我希望也可以通过它添加注释。实际上,我已经通过视图中的form\u valid方法完成了我想要的,方法是在保存表单之后添加:item.comments\u set.create(Comment=\u Comment),其中_Comment是form.cleaned\u data.get('comments')。
item = Item.objects.get(pk=<item_id>)
item = Item.objects.create(<item_properties_here>)
comment = form.save()
comment.item = item.
comment.save()
item = Item.objects.get(pk=<item_id>)
comment = form.save()
item.comments_set.add(comment)
item.save()