python - Django表单Form.save()问题
问题描述
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 = 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).网页错误: comment.save() ...▼ Local varsVariable ValuearticleId ’336’comment <CommentForm bound=False, valid=False, fields=(content)>content ’你好’request <WSGIRequest: POST ’/article/commentCreate/336/’>
如何将文章对应的articleId 的值放进CommentForm()?
问题解答
回答1:根据articleId获取到Article: obj = Article.objects.get(id=articleId)然后 comment.article = obj # 具体看你在models里定义的article字段名
回答2:嗯,谢谢你,这个问题我在http://zmrenwu.com/post/14/ 里面已经找到解决方法了。不过这个论坛怎么把提问删掉。
相关文章:
1. javascript - 在 model里定义的 引用表模型时,model为undefined。2. css3 - 这个右下角折角用css怎么画出来?3. javascript - canvas 裁剪空白区域4. atom开始输入!然后按tab只有空格出现没有html格式出现5. css3 - 没明白盒子的height随width的变化这段css是怎样实现的?6. java - 我设置了cookie的max age,但是cookie依然在关闭游览器后消失了7. apache - 想把之前写的单机版 windows 软件改成网络版,让每个用户可以注册并登录。类似 qq 的登陆,怎么架设服务器呢?8. android - 课程表点击后浮动后边透明可以左右滑动的界面是什么?9. python3.x - c++调用python310. java - 根据月份查询多个表里的内容怎么实现好?
