0

在我的视图函数中,我将表单发送到端点,然后我收到 JSON 响应。提交表单后,响应会显示在模板上。

问题是响应中的一个键是一张以 base64url 编码的照片。例如:

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

我想要实现的是解码 base64url 并在网页上呈现图像。

这是我的视图功能:

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)

这是我的模板:

<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 %}
4

1 回答 1

1

您需要将 base64 显示为 img soure。

{% for val in response %}
    <tr>                
        <td>{{ val.tracking_id }}</td>
        <td><img src="{{ val.photo }}"></td> 
    </tr>
{% endfor %}
于 2021-04-11T15:49:10.097 回答