python - Django表单Form.save()问题

查看:160
本文介绍了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 = 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()?

解决方案

根据articleId获取到Article: obj = Article.objects.get(id=articleId)
然后 comment.article = obj # 具体看你在models里定义的article字段名

这篇关于python - Django表单Form.save()问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆