基于全局变量值django中间件的更新模型

时间:2018-10-28 04:45:11

标签: python django django-middleware

is_paid_member=False #Global variable

功能:

  global is_paid_member
if is_paid_member == True:
    with transaction.atomic():
        client = ClientProfile.objects.get(user=request.user)
        client.subscription = "Member"
        client.save(update_fields=['subscription'])

我想根据全局变量的值更新模型。如果付款,此函数必须更新模型。在哪里放置此函数以更新模型字段?

在交易成功功能中将is_paid_member更改为True

@csrf_exempt
def payment_success_member(request):
data = {}
global is_paid_member
is_paid_member=True

user=request.user

return render(request, 'payu_success.html',data)

这是付款功能:

@login_required(login_url='/account/login/')
def MemberPay(request):
data = {}
global is_paid_member

if is_paid_member == True:
    with transaction.atomic():
        client = ClientProfile.objects.get(user=request.user)
        client.subscription = "Member"
        client.save(update_fields=['subscription'])
txnid = get_transaction_id()
hash_ = generate_hash_member(request, txnid)
hash_string = get_hash_string_member(request, txnid)
# use constants file to store constant values.
# use test URL for testing
data["action"] = constants.PAYMENT_URL_TEST
amounts = Amount.objects.filter(subscription="Member")

data["amount"] =amounts[0].amount
data["productinfo"] = constants.PAID_FEE_PRODUCT_INFO
data["key"] = config.KEY
data["txnid"] = txnid
data["hash"] = hash_
data["hash_string"] = hash_string
data["firstname"] = request.user.username
data["email"] = request.user.email
data["subscription"] = "Free"

if (request.user.is_client == True):
    data["phone"] = request.user.client_profile.mobile_number
else:
    data["phone"] = request.user.trainer_profile.mobile_number
data["service_provider"] = constants.SERVICE_PROVIDER
data["furl"] = 
request.build_absolute_uri(reverse("student:payment_failure_member"))
data["surl"] = 
request.build_absolute_uri(reverse("student:payment_success_member"))
if request.user.client_profile.subscription=="Fellow":
    data["subscription"]="Fellow"
if request.user.client_profile.subscription=="Member":
    data["subscription"]="Member"
global is_paid_member
print("PAID: ",is_paid_member)
print(data["subscription"])

if is_paid_member==True:
    with transaction.atomic():
     client= ClientProfile.objects.get(user=request.user)
     client.subscription="Member"
     client.save(update_fields=['subscription'])

return render(request, "payu_payment_member.html", data)

1 个答案:

答案 0 :(得分:0)

在模型中创建一个Boolean field

class Payment(models.Model):
   ....
   ....
   is_paid_member = models.BooleanField(default=False)
   ....

现在,在回调函数payment_success_member()中,使用txn_id获取付款模型对象并更新is_paid_member字段:

def payment_success_member(request):
    .....
    txn_id = request.data['txn_id']
    payment_obj = Payment.object.get(txn_id=txn_id)
    payment_obj.is_paid_member =True
    payment_obj.save()
    .....