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

时间:2018-10-03 13:21:27

标签: python django

我写了两类,一类用于发布付款数据,另一类用于显示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')

我该如何实现?预先感谢。

2 个答案:

答案 0 :(得分:1)

1。最简单的方法

urls.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。使用会话的另一种方法:

urls.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 :(得分:0)

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

提示:

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

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

  

注意

     

您可能还想阅读有关Form views的信息,这种视图具有一个名为success_url的属性。敲钟?