使用Django构建个人网站(十一)——注册内容追加,后台存入数据库

之前写前端,就感觉难度颇大,好在自己克服了其中的困难。但是今天在后台数据保存时候,遇到了一些难题,我必须要记录下来,作为教训。

报错内容

django.db.utils.IntegrityError: NOT NULL constraint failed: account_userprofile.user_id
报错内容看起来很简单,但是我却一直都不知道为什么,我原来的视图函数是这样写的。

def user_signup(request):
    if request.method == 'GET':
        return render(request, 'account/signUp.html')
    else:
        user = User()
        userprofile = userProfile()
        user.password = request.POST['password']
        userProfile.user = user
        userProfile.mobile = request.POST['mobile']
        userProfile.email = request.POST['email']
        userProfile.nickname = request.POST['nickname']
        userProfile.QQ = request.POST['QQ']
        user.save()
        userProfile.save()
        return HttpResponse("提交成功")

我还觉得没问题,对啊,看起来是没问题。创建两个表,然后一对一关联。我百思不得其解。后来看到这篇博文
django ORM详解
我才明白了一对一、一对多、多对多的不同魔性的方式是不同的。我不能只创建一个空白的表格,必须用相应的方法才行。
所以我改写了代码

def user_signup(request):
    if request.method == 'GET':
        return render(request, 'account/signUp.html')
    else:
        user = User.objects.create_user(username=request.POST['username'])
        userProfile = UserProfile.objects.create(user=user)
        user.password = request.POST['password']
        userProfile.user = user
        userProfile.mobile = request.POST['mobile']
        userProfile.email = request.POST['email']
        userProfile.nickname = request.POST['nickname']
        userProfile.QQ = request.POST['QQ']
        user.save()
        userProfile.save()
        return HttpResponse("提交成功")

总结

不会报错了,成功!自己的基础知识掌握还是有点不牢固,以为自己对django的理解很深刻了,实际上做实战的时候发现还是需要各种查资料,不然寸步难行。

下集预告

注册模块完成了,我就要完成评论、点赞、浏览以及侧边栏了!这些完成了,一个基本博客就算完成了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值