0

I have a long python function and within the function I am generating a voucher which I would want to autofill in my HTML page. Kindly assist

The full function:

def confirmation(request):
    print("Start MpesaCallback")
    global profile
    
    mpesa_body = request.body.decode('utf-8')
    mpesa_body = json.loads(mpesa_body)
    print(mpesa_body)
    print("Mpesa Body")

    merchant_requestID = mpesa_body["Body"]["stkCallback"]["MerchantRequestID"]
    print('merchant_requestID: ', merchant_requestID)
    checkout_requestID = mpesa_body["Body"]["stkCallback"]["CheckoutRequestID"]
    print('checkout_requestID: ', checkout_requestID)
    result_code = mpesa_body["Body"]["stkCallback"]["ResultCode"]
    print('result_code: ', result_code)
    result_desc = mpesa_body["Body"]["stkCallback"]["ResultDesc"]
    print('result_desc: ', result_desc)
    metadata = mpesa_body["Body"]["stkCallback"]["CallbackMetadata"]["Item"]
    for item in metadata:
        title = item["Name"]
        if title == "Amount":
            amount = item["Value"]
            print('Amount: ', amount)
        elif title == "MpesaReceiptNumber":
            mpesa_receipt_number = item["Value"]
            print('Mpesa Reference No: ', mpesa_receipt_number)
        elif title == "TransactionDate":
            transaction_date = item["Value"]
            print('Transaction date: ', transaction_date)
        elif title == "PhoneNumber":
            phone_number = item["Value"]
            print('Phone Number: ', phone_number)

    str_transaction_date = str(transaction_date)
    trans_datetime = datetime.strptime(str_transaction_date, "%Y%m%d%H%M%S")
    tz_trans_datetime = pytz.utc.localize(trans_datetime)

    payment = MpesaPayment.objects.create(
        MerchantRequestID=merchant_requestID,
        CheckoutRequestID=checkout_requestID,
        ResultCode=result_code,
        ResultDesc=result_desc,
        Amount=amount,
        MpesaReceiptNumber=mpesa_receipt_number,
        TransactionDate=tz_trans_datetime,
        PhoneNumber=phone_number,
    )
    if result_code == 0:
        payment.save()
        print("Successfully saved")

        password_length = 5
        voucher = secrets.token_urlsafe(password_length)

        print(voucher)

        headers = {
            'Content-Type': 'application/json',
            'h_api_key': os.getenv("SMS_Token"),
            'Accept': 'application/json'
        }
        payload = {
            "mobile": phone_number,
            "response_type": "json",
            "sender_name": "23107",
            "service_id": 0,
            "message": "Your WiFi Voucher is " + voucher + ".\nAirRumi."
        }
        response = requests.request("POST", 'https://smsdomain.com/sms/sendsms', headers=headers,
                                    json=payload)
        r = response.json()
        print(r)
        print("SMS Sent")

        print(amount)

        if amount == 1:
            profile = 'one_hour'
        elif amount == 50:
            profile = 'one_day'
        elif amount == 300:
            profile = 'one_week'
        elif amount == 1000:
            profile = 'one_month'
        else:
            print('Incorrect Amount')

        print(profile)

        connection = routeros_api.RouterOsApiPool(
            host=os.getenv("ip"),
            username=os.getenv("usernamee"),
            password=os.getenv("password"),
            port=8728,
            use_ssl=False,
            ssl_verify=False,
            ssl_verify_hostname=True,
            ssl_context=None,
            plaintext_login=True
        )
        api = connection.get_api()

        user = api.get_resource('/ip/hotspot/user')
        user.add(name=voucher, server="hotspot1", password='1234', profile=profile)

        print("User " + voucher + " created.")

    else:
        print("Payment was not successful")

    context = {
        "resultcode": result_code,
        "resultdesc": result_desc
    }

    if context['resultcode'] == 0:
        return JsonResponse(dict(context))

My HTML page that I want auto filled:

<form name="login" action="http://mydomain/login" method="post">
                {% csrf_token %}
                <input type="hidden" name="dst" value="https://www.google.com"/>
                <input type="hidden" name="popup" value="true"/>

                <label>
                   <input type="text" name="username" value="{{ voucher }}" placeholder="Enter your Voucher" required>
                </label>
                <label>
                    <input type="hidden" name="password" value="1234">
                </label><br><br>
                <div id="login-button"><input type="submit" value="CONNECT"/></div>
            </form>

How do I get the voucher generated and auto fill it in the HTML? I have used the {{ voucher }} and its not working. I have updated the whole function but not the whole view.py

12
  • stackoverflow.com/a/31966504/19152434 <br/> Maybe use something like flask? Commented Jan 31, 2023 at 7:24
  • Do you use Django? Commented Jan 31, 2023 at 7:25
  • What framework do you use? Commented Jan 31, 2023 at 9:25
  • Am using Django Commented Feb 1, 2023 at 6:07
  • you have to use render to process your template and pass your voucher (or response) in context parameter? Commented Feb 1, 2023 at 6:09

1 Answer 1

1

You can use render for django.shortcuts module:

from django.shortcuts import render

def confirmation(request):
   # Your code here
   ...
    context = {
        "resultcode": result_code,
        "resultdesc": result_desc,
        "voucher": voucher,  # <- HERE
    }

    # Comment
    # if context['resultcode'] == 0:
    #    return JsonResponse(dict(context))

   return render(request, 'your_template.html', context=context)
Sign up to request clarification or add additional context in comments.

10 Comments

return render(request, 'your_template.html', context={'voucher': voucher}) this should be the last line in the function?
Yes, that's right.
Its still not retrieving the voucher
You have to modify the end of your function. I updated my answer.
Thank you, working well in postman, let me try in production.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.