python - Django表單Form.save()問題
伊谢尔伦
伊谢尔伦 2017-05-24 11:34:50
0
2
888
def commentCreate(request, articleId):    
#POST
'''
the problem is  comment no relate mapping to one id of Artilce
    单纯的将CommentForm().save 是无法实现留言的,因为
    创建一个留言需要对应一个文章,即要对应其文章所属id;
'''
content = request.POST.get('comment')

CommentForm.content = content


comment = CommentForm()    
#print ('表单绑定确认:',comment.is_bound)
'''
if not comment.is_valid():
    return render(request, template,{'article':articleId})
'''
comment.save()
messages.success(request,'留言已新增')
return redirect('article:articleRead',articleId=articleId)

Console错误:
django.db.utils.IntegrityError: 错误:  在字段 "article_id" 中空值违反了非空约束
DETAIL:  失败, 行包含(879, , null, 2017-05-22 11:05:06.862614+00, null).


网页错误:
    comment.save() ...
▼ Local vars
Variable    Value
articleId    
'336'
comment    
<CommentForm bound=False, valid=False, fields=(content)>
content    
'你好'
request    
<WSGIRequest: POST '/article/commentCreate/336/'>

如何將文章對應的articleId 的值放進CommentForm()?

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

全部回覆(2)
刘奇

根據articleId取得到Article: obj = Article.objects.get(id=articleId)
然後 comment.article = obj # 具體看你在models裡定義的article字段名

phpcn_u1582

嗯,謝謝你,這個問題我在http://zmrenwu.com/post/14/ 裡面已經找到解決方法了。不過這個論壇怎麼把提問刪掉。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!