python - Django表單Form.save()問題
問題描述
def commentCreate(request, articleId): #POST’’’the problem is comment no relate mapping to one id of Artilce 單純的將CommentForm().save 是無法實現(xiàn)留言的,因為 創(chuàng)建一個留言需要對應一個文章,即要對應其文章所屬id;’’’content = request.POST.get(’comment’)CommentForm.content = contentcomment = 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).網(wǎng)頁錯誤: comment.save() ...▼ Local varsVariable ValuearticleId ’336’comment <CommentForm bound=False, valid=False, fields=(content)>content ’你好’request <WSGIRequest: POST ’/article/commentCreate/336/’>
如何將文章對應的articleId 的值放進CommentForm()?
問題解答
回答1:根據(jù)articleId獲取到Article: obj = Article.objects.get(id=articleId)然后 comment.article = obj # 具體看你在models里定義的article字段名
回答2:嗯,謝謝你,這個問題我在http://zmrenwu.com/post/14/ 里面已經(jīng)找到解決方法了。不過這個論壇怎么把提問刪掉。
相關文章:
1. angular.js - 各位大神們,你們混合開發(fā),web方式中更推薦用什么框架呀? react?vue?angular?謝謝~2. angular.js - angularjs的自定義過濾器如何給文字加顏色?3. angular.js使用$resource服務把數(shù)據(jù)存入mongodb的問題。4. docker-machine添加一個已有的docker主機問題5. javascript - htaccess rewrite 的問題6. javascript - IOS微信audio標簽不能通過touchend播放7. 前端 - 集思廣益,如何用CSS實現(xiàn)數(shù)字上面有一個點8. PHP類中的$this9. 老師百度網(wǎng)盤分享一下WampServer的包啊,我們下載幾kb要下載一天的.10. html5 - vuex 為什么需要action,我發(fā)現(xiàn)進行異步操作回調(diào)中直接操作mutation也沒有報錯
