为什么 Django 表单在波斯语中显示 UnicodeEncodeError?

问题描述 投票:0回答:2

我的简单表格如下:

forms.py:

from django import forms
class NameForm(forms.Form):
    your_name = forms.CharField(label='Your name', max_length=100)

views.py:

from django.http import HttpResponseRedirect
from django.shortcuts import render

from .forms import NameForm


def get_name(request):
    if request.method == 'POST':
        form = NameForm(request.POST)
        if form.is_valid():
            print(form.cleaned_data)
            return HttpResponseRedirect('/')
    else:
        form = NameForm()
    return render(request, 'form.html', {'form': form})

form.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form action="/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit">
</form>
</body>
</html>

如果我写英文字符并提交表单,它可以正常工作并执行打印语句,但如果我写波斯语字符,如“เกงององ”,它会显示此错误:

UnicodeEncodeError at /
'charmap' codec can't encode characters in position 132-136: character maps to <undefined>
Request Method: POST
Request URL:    http://127.0.0.1:8000/
Django Version: 4.1.7
Exception Type: UnicodeEncodeError
Exception Value:    
'charmap' codec can't encode characters in position 132-136: character maps to <undefined>
Exception Location: C:\Program Files\Python311\Lib\encodings\cp1252.py, line 19, in encode
Raised during:  myapp.views.get_name
Python Executable:  C:\python\test1\venv\Scripts\python.exe
Python Version: 3.11.2
Python Path:    
['C:\\python\\test1',
 'C:\\python\\test1',
 'C:\\Program Files\\JetBrains\\PyCharm '
 '2022.3.2\\plugins\\python\\helpers\\pycharm_display',
 'C:\\Program Files\\Python311\\python311.zip',
 'C:\\Program Files\\Python311\\DLLs',
 'C:\\Program Files\\Python311\\Lib',
 'C:\\Program Files\\Python311',
 'C:\\python\\test1\\venv',
 'C:\\python\\test1\\venv\\Lib\\site-packages',
 'C:\\Program Files\\JetBrains\\PyCharm '
 '2022.3.2\\plugins\\python\\helpers\\pycharm_matplotlib_backend']
Server time:    Tue, 14 Mar 2023 19:06:06 +0000

The string that could not be encoded/decoded was: lue="متن تست

我该怎么办?

我尝试使用下面的链接,但它在 Django 中没有帮助我:

UnicodeEncodeError:“charmap”编解码器无法对字符进行编码

python django django-views django-forms django-templates
2个回答
3
投票

发生该错误是因为系统控制台使用的字符编码无法处理波斯语字符。要解决此问题,您可以在 Django

UTF-8
文件中将默认编码设置为
settings.py
,如下所示:

import sys
import io

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

此代码将标准输出的默认编码设置为 UTF-8,它可以处理 非 ASCII 字符。

此外,HTML 应具有以下内容:

<meta charset="utf-8">

这告诉浏览器使用 UTF-8 编码来显示文本。

此外,我还建议您在表格无效时进行条件检查,例如:

from django.shortcuts import redirect 

def get_name(request):
    if request.method == 'POST':
        form = NameForm(request.POST)
        if form.is_valid():
            print(form.cleaned_data)
            return HttpResponseRedirect('/')
        else:
            return redirect('some_error_page')
    else:
        form = NameForm()
    return render(request, 'form.html', {'form': form})

0
投票

当我开始学习Django时,我做了一个函数,但是因为我使用了波斯语单词,结果我得到了这样的答案:{"title": "\u0645\u0642\u0627\u0644\u0647 \u0627\u0648\u0644 ", "id": 20, "slug": "第一篇文章"} 解决这个问题的方案是什么? 功能: def api(请求): 数据={ "title":"标题", “id”:20, "slug":"第一篇文章" } 返回 JsonResponse(数据)

© www.soinside.com 2019 - 2024. All rights reserved.