我正在创建一个网站,用户可以在其中发布内容,每个内容都会重定向到私人用户进行用户聊天,具体取决于内容ID。
我这样做,所以我可以在私人聊天中检索内容信息。
问题是当用户提交表单以发布comment
时,我收到此错误:
无法指定"<用户:my_user>":" userComment.seller"必须是"简介"实例
在我看来,我将关联用户保存为buyer
,并将用seller
收到评论的用户。
如何修复此错误?我在下面的代码上做错了什么?
这里是 models.py :
class Profile(models.Model):
name = models.CharField(max_length=120)
user = models.OneToOneField(User, null=True, blank=True)
class Gig(models.Model):
profile = models.ForeignKey(Profile, null=True)
title = models.CharField(max_length=100, unique=True)
class userComment(models.Model):
buyer = models.ForeignKey(User, related_name="buyer", null=True)
seller = models.ForeignKey(Profile, related_name="seller", null=True)
comment = models.TextField(max_length=255, null=True)
views.py
def addComment(request, gig_id):
gig = Gig.objects.get(id=gig_id)
username = gig.profile.user
if request.method == 'POST':
form = userCommentForm(request.POST, request.FILES)
if form.is_valid():
form.save(buyer=request.user)
return HttpResponseRedirect('/')
else:
form = userCommentForm()
form.fields['seller'].initial = username
forms.py
class userCommentForm(forms.Form):
seller = CommaSeparatedUserField(label=_(u"seller"))
comment = forms.CharField(label=_(u"comment"), widget=forms.Textarea())
def save(self, buyer):
sellers = self.cleaned_data['seller']
comment = self.cleaned_data['comment']
message_list = []
for seller in sellers:
msg = userComment(buyer=buyer, seller=seller, comment=comment,)
if seller == buyer:
print('-----------------------------------------------')
print('same')
if None is not None:
msg.parent_msg = None
None.save()
msg.save()
message_list.append(msg)
return message_list
追溯:
File "C:\Python34\projects\tryTen\private_comment\views.py" in addComment
31. form.save(buyer=request.user)
File "C:\Python34\projects\tryTen\private_comment\forms.py" in save
15. msg = userComment(buyer=buyer, seller=seller, comment=comment,)
答案 0 :(得分:2)
您的userComment
模型将feild seller
作为另一个名为Profile
的模型的外键。但是,msg = userComment(buyer=buyer, seller=seller, comment=comment,)
中传递的买方实例属于User
类型而非Profile
类型。
要么修改
seller = models.ForeignKey(Profile, related_name="seller", null=True)
到seller = models.ForeignKey(User, related_name="seller", null=True)
要么
检索并传递Profile
实例。
p = Profile.objects.get(user=seller)
msg = userComment(buyer=buyer, seller=p, comment=comment)
答案 1 :(得分:1)
您的CommaSeparatedUserField用户字段似乎是您尚未与我们分享的自定义字段。但是,很容易看出您的cleaning_data实际上是卖家名称列表而不是Seller
个实例。如果另一方面它包含id,你可以这样做:
msg = userComment(buyer=buyer, seller_id=seller, comment=comment,)
如果它只是名称
sl = Profile.objects.get(name=seller) # adjust this according to your model
msg = userComment(buyer=buyer, seller_id=sl, comment=comment,)