pythondjangobase64base64url

Django - How to decode a base64url and render it in Django template


In my view function, I am sending a form to an endpoint then I receive a response in JSON. The response is then displayed on the template after the form has been submitted.

The problem is that a key in the response is a photo that is encoded in base64url. e.g:

{"photo": "a very long base64url"}

What I want to achieve is to decode that base64url and render the image on the webpage.

Here's my view function:

def post_nin(request):
    if request.method == 'POST':
        form = NINPostForm(request.POST)
        if form.is_valid():
            nin = form.cleaned_data['nin']
            url = request.build_absolute_uri(reverse_lazy('nin_verification',
                                                          kwargs={'nin': nin},
                                                          ))
            r = requests.get(url=url)
            resp = r.text
            resp_json = json.loads(resp)
            resp_list = resp_json['data'] # [{'tracking_id':12345, 'photo':'base64url'}]

            return render(request, 'ninsuccess.html', {'response': resp_list})
    else:
        form = NINPostForm()
    context = {'form': form, }

    return render(request, 'ninform.html', context)

Here is my template:

<table class="">
    <thead>
    <tr>           
        <th>Tracking ID</th>
        <th>Picture</th>        
    </tr>
    </thead>
    <tbody>
    {% for val in response %}
        <tr>                
            <td>{{ val.tracking_id }}</td>
            <td>{{ val.photo }}</td> # a long base64url is displayed which is not what I want
        </tr>
    {% endfor %}

Solution

  • You need to display the base64 as img soure.

    {% for val in response %}
        <tr>                
            <td>{{ val.tracking_id }}</td>
            <td><img src="{{ val.photo }}"></td> 
        </tr>
    {% endfor %}