Django-从视图调用celery任务

时间:2019-02-07 22:29:10

标签: python django task celery

我想从我的views.py调用一个芹菜任务,但是由于某种原因,我收到以下错误消息:

  

/ user / wallet_deposit处的NoReverseMatch反向   找不到参数的“ wallet_deposit_gen_new_addr_btc”。 1个   尝试过的模式:['user / wallet_deposit / new_addr_btc /(?P \ d +)/ $']

views.py

def wallet_deposit(request, pk=None):
        if pk:
            user = request.user
        else:
            user = request.user
        args = {'user': user}
        return render(request, 'MyProject_Accounts/wallet_deposit.html', args)



def wallet_deposit_gen_new_addr_btc(request):
    user = request.user
    if request.method == 'GET':
        allocate_new_btc_address.delay(user.pk)
    else:
        user = request.user
    args = {'user': user}
    return render(request, 'MyProject_Accounts/wallet_deposit.html', args)

tasks.py

def allocate_new_btc_address(user_pk):
    user = User.objects.get(pk=user_pk)
    new_address = subprocess.Popen(['electrum', 'createnewaddress'])
    try:
        user = user.objects.update_or_create(acc_btc_addr=new_address)
        user.save()
        print(new_address)
        logger.info("New BTC address has been allocated to a user account")
    except Exception as e:
        print(e)

urls.py

url(r'^home/wallet_deposit/$',  auth_required(MyProject_Accounts.wallet_deposit), name='wallet_deposit'),
url(r'^home/wallet_deposit/new_addr_btc/$', auth_required(MyProject_Accounts.wallet_deposit_gen_new_addr_btc), name='wallet_deposit_gen_new_addr_btc'),

预先感谢

2 个答案:

答案 0 :(得分:0)

您的user = get_user_model.objects.get(pk=pk)行应更改为user = get_user_model().objects.get(pk=pk)get_user_model是一种返回项目默认用户模型的方法。直到您将函数括号放在get_user_model之后,get_user_model()方法才会被调用。

答案 1 :(得分:0)

您没有在URL中传递用户的pk,因此它始终为None,并且具有pk=None的用户不存在。您应该将pk添加到网址中,例如url(r'^user/wallet_deposit/new_addr_btc/(?P<pk>\d+)$', MyProject_Accounts.wallet_deposit_gen_new_addr_btc, name='wallet_deposit_gen_new_addr_btc')。用户还应该能够到达正确的URL(您应该正确生成链接)。 也许,作为用户,我应该只能更改我的帐户?如果是这样,您应该像在else块中一样从请求中获取经过身份验证的用户