一:模型类直接从把前端表单传入的值,进行存储。

@csrf_exempt
def regist(request):
    if request.method == 'POST':
        form = UserForm(request.POST)  # 从前端表单中获取的数据,传给用户模型类,创建实例。
        username = request.POST.get('username')
        farm_name = request.POST.get('farm_name')
        address = request.POST.get('address')
        phone = request.POST.get('phone')
        if form.is_valid():
            user = form.save()  # 验证成功
            #将用户信息(id, nickname, photo)保存到session中
            request.session['login_user'] = json.dumps({'id': user.id,
                                                        'nickname': user.nickname
                                                        })
            cowObj = Sheep_Farm.objects.filter(farm_name=farm_name)
            if cowObj.count() != 0:
                user_id = cowObj[0].user_id
            else:
                user_id = UserProfile.objects.get(username=username).id
            Sheep_Farm.objects.create(
                username=username,
                farm_name=farm_name,
                address=address,
                phone=phone,
                user_id=int(user_id),
            )
            return JsonResponse({'message': '注册成功!', 'session': request.session['login_user']})
        else:
            errors = json.loads(form.errors.as_json())
            messages = [error for error in errors]
            message = errors[messages[0]][0]['message']
            return JsonResponse({'message': message,'status':'0'})
01-12 08:26