【问题标题】:Django - How to decode a base64url and render it in Django templateDjango - 如何解码 base64url 并在 Django 模板中呈现它
【发布时间】:2021-04-11 14:26:35
【问题描述】:

在我的视图函数中,我正在向端点发送一个表单,然后我收到 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 %}

【问题讨论】:

    标签: python django base64 base64url


    【解决方案1】:

    你需要将base64显示为img soure。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-08
      • 2019-10-27
      • 1970-01-01
      • 1970-01-01
      • 2011-07-17
      • 1970-01-01
      • 1970-01-01
      • 2020-06-15
      相关资源
      最近更新 更多