繁体   English   中英

将值从一个类/函数传递到另一个类/函数

[英]pass value from one class/function to another class/function

我写了两个类,一类用于发布付款数据,另一类用于显示带有order_id付款成功消息。 我正在从第一个函数发送订单 ID,我想捕获此 ID 以显示在我的付款成功模板中。

class ApiVIew(TemplateView):
    template_name = 'payment.html'
    def post(self,request):
        r = requests.post(url='www.randomsite.com',params = {'authToken':'12345','card_no':'1234','card_cvv':'****'})
        return HttpResponse(json.dumps({'response':r.json(),'status':'ok'}))

我称这个类是 ajax 并在那里解析,所以如果 r 没有给出错误,那么我将( window.location=localhost:8000/success )重定向到success-payment.html页面。 所以响应给了我一个json数据:

{'isSuccess':1,'order_id':1cq2,}

所以我想得到这个order_id并将它传递给下面写的另一个函数/类。

def payment_successfullView(request):
    return render(request,'payment-successfull.html')

我怎样才能做到这一点? 提前致谢。

1.最简单的方法

网址.py:

...
path('<str:order_id>/success/', views.payment_successfullView, name='success'),
...

意见:

from django.shortcuts import redirect, reverse
class ApiVIew(TemplateView):
    template_name = 'payment.html'
    def post(self, request):
        r = requests.post(url='www.randomsite.com',params = {'authToken':'12345','card_no':'1234','card_cvv':'****'})
        if r.isSuccess:
            return redirect(reverse('success', args=(r.order_id, )))
        # do your stuff in case of failure here

def payment_successfullView(request, order_id):
    return render(request,'payment-successfull.html', {
        'order_id': order_id,
    })

2. 另一种使用会话的方法:

网址.py:

...
path('success/', views.payment_successfullView, name='success'),
...

意见:

from django.shortcuts import redirect, reverse
from django.http import HttpResponseForbidden

class ApiVIew(TemplateView):
    template_name = 'payment.html'
    def post(self, request):
        r = requests.post(url='www.randomsite.com',params = {'authToken':'12345','card_no':'1234','card_cvv':'****'})
        if r.isSuccess:
            request.session['order_id'] = r.order_id  # Put order id in session
            return redirect(reverse('success', args=(r.order_id, )))
        # do your stuff in case of failure here

def payment_successfullView(request):
    if 'order_id' in request.session:
        order_id = request.session['order_id']  # Get order_id from session
        del request.session['order_id']  # Delete order_id from session if you no longer need it
        return render(request,'payment-successfull.html', {
            'order_id': order_id,
        })

    # order_id doesn't exists in session for some reason, eg. someone tried to open this link directly, handle that here.
    return HttpResponseForbidden()

好的,我认为最好的答案为您指明了正确的方向,让您找出有趣的部分。

提示:

  1. 您的APIView必须重定向payment_successfullView
  2. 您有order_id因此您可以使用DetailView
  3. 如果要显示订单列表(order_id),请使用ListView

我认为使用这些技巧,你会没事的。 快乐编码。

笔记

您可能还想了解Form 视图,此类视图有一个名为success_url的属性。 按门铃?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM