【问题标题】:Convert Charfield to string in Python在 Python 中将 Charfield 转换为字符串
【发布时间】:2021-08-24 15:01:20
【问题描述】:

我希望能够使用 Python 在 PostgreSQL 数据库中保存换行符,但是当检索保存的并在控制台中打印或将其作为上下文发送到模板时(我正在 Django 中开发项目),行不应用中断。

>>> from apps.prestamos.models import Aprobado
>>> model = Aprobado.objects.last()
>>> print('First comment \n Second comment')
First comment
Second comment
>>> print(model.notas)
First comment \n Second comment
>>> print(str(model.notas))
First comment \n Second comment
>>>

信息通常通过 POST 从客户端添加。

....
model.notas = request.POST['notas']
model.save()

'request.POST' 是一个字典。

【问题讨论】:

  • 您能告诉我们您是如何将它添加到数据库中的吗?
  • 我用你提到的细节更新了问题。
  • 我怀疑你的问题是换行符是用request.POST编码的,而不是从数据库中检索数据。
  • 如何解码“request.POST”?
  • 那么您是在客户端输入的字面上输入\n 吗?您实际上需要在那里添加一个新行(即实际按下回车键)......此外,HTML 默认情况下不会呈现换行符,您会发现该部分有很多重复的问题。

标签: python django postgresql


【解决方案1】:

请检查一下 Django 和 Python 的版本是不是最新的。

我使用 python==3.8 和 Django==3.2.6 运行下面的代码

>>> from core.models import Inspector
>>> ins = Inspector.objects.last()
>>> ins.address

o/p:- '\n换行\n测试'

>>> print(ins.address)

o/p:- 这 新队 测试

please check the screenshot of the output

【讨论】:

    猜你喜欢
    • 2020-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    • 2021-05-14
    • 2012-06-14
    • 1970-01-01
    相关资源
    最近更新 更多