views.py
def crave_view(request):
if (request.method=="POST"):
form1=CraveDataForm(request.POST, request.FILES)
form2 = CraveReplyForm(request.POST, request.FILES)
print form1
print form2
if form1.is_valid() and form2.is_valid():
crave_made = form1.save(commit=False)
crave_made.person = request.user
crave_made.save()
reply = form2.save(commit=False)
reply.person=request.user
reply.save()
#login(request,crave_made.username,form1.clean_password2())
messages.success(request, 'You Registered Successfully')
#return HttpResponseRedirect('/details/')
else:
print form1
print form2
messages.error(request, 'Please enter all required fields')
else:
form2 = CraveReplyForm()
form1=CraveDataForm()
return render(request, "crave/crave.html", { 'form1' : form1, 'form2' : form2 })
models.py
class crave_data(models.Model):
person = models.ForeignKey(User)
post=models.TextField(blank = True,null = True)
date= models.DateTimeField(auto_now_add=True, blank=True)
def __unicode__(self):
return self.post
class comments(models.Model):
crave=models.ForeignKey(crave_data)
reply=models.CharField(max_length=1000, blank = True,null = True)
date= models.DateTimeField(auto_now_add=True, blank=True)
def __unicode__(self):
return self.reply
forms.py
class CraveDataForm(forms.ModelForm):
class Meta:
model = crave_data
exclude=['date', 'password1', 'password2', 'username', 'person']
class CraveReplyForm(forms.ModelForm):
class Meta:
model = comments
exclude=['date', 'crave', 'password1', 'password2', 'username']
我的form1正在验证并在后端保存但是form2没有保存在后端。错误在“reply.person = request.user”行中,错误是“crave_comments.crave_id可能不为NULL” 请帮助我,我想保存评论,即回复那个perticuler crave_made即发布
答案 0 :(得分:0)
保存表单时,您是否尝试过使用commit = True?您收到的错误告诉您,在添加外键关系之前需要保存回复。
答案 1 :(得分:0)
在保存和创建reply
时,您还需要指定crave
属性。
将您的代码更新为
reply = form2.save(commit=False)
reply.person=request.user
reply.crave = crave_made
reply.save()
假设您要使用之前创建的crave_made
进行保存。