【问题标题】:Django form textarea strips newlinesDjango form textarea 去掉换行符
【发布时间】:2015-09-09 14:25:06
【问题描述】:

我可能遗漏了一些明显的东西,但我无法让 Django 正确显示换行符 文本区域。我正在使用 Python 3.4 和 Django 1.8.3。

例如,假设我有一个模型:

class Product(models.Model):
    description = models.TextField()

还有一个管理员:

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    pass

如果通过管理员添加新产品,请使用以下说明:

First line

Second line

然后点击保存,以下值保存在数据库中(例如,我可以通过 django 的 shell 访问它):

>>> product.description
'First line\r\n\r\nSecond line'

但是当我尝试编辑相同的产品时,textarea 会显示:

First line
Second line

所以如果对其他字段进行一些修改,当我点击保存时,我的换行符会丢失。

抱歉这个愚蠢的问题,但我做错了什么?

【问题讨论】:

    标签: python django forms


    【解决方案1】:

    我做了同样的例子并且工作正常。 您使用的是什么版本的 django?
    唯一的区别是打开 django shell 时,描述是 unicode。
    这将是问题所在。
    结果是:

    >>> from product.models import Product
    >>> o = Product.objects.all().first()
    >>> o.description
    u'First Line\r\n\r\nSecond line'
    

    【讨论】:

    • 我使用的是 Python 3.4 和 django 1.8.3。由于您无法重现该问题,因此我必须在某个地方介绍它,谢谢您的尝试:)
    • 我在 python2.7 和 django 1.7.2 上进行了测试。太好了,你解决了问题!
    【解决方案2】:

    好的,这是由 StripWhitespaceMiddleware 介绍的,我已经准备好减小 HTML 大小:

    class StripWhitespaceMiddleware(object):
        """
        Strips leading and trailing whitespace from response content.
        """
    
        def __init__(self):
            self.whitespace = re.compile('^\s*\n', re.MULTILINE)
            self.whitespace_lead = re.compile('^\s+', re.MULTILINE)
            self.whitespace_trail = re.compile('\s+$', re.MULTILINE)
    
        def process_response(self, request, response):
            if "text" in response.get('Content-Type', ''):
                response_content = response.content.decode('utf-8')
                if hasattr(self, 'whitespace_lead'):
                    response_content = self.whitespace_lead.sub('', response_content)
                if hasattr(self, 'whitespace_trail'):
                    response_content = self.whitespace_trail.sub('\n', response_content)
    
                # Uncomment the next line to remove empty lines
                if hasattr(self, 'whitespace'):
                    response_content = self.whitespace.sub('', response_content)
                response.content = response_content.encode('utf-8')
    
            return response
    

    当我禁用此中间件时,Textareas 会按预期工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-13
      • 2014-08-29
      • 1970-01-01
      • 2012-02-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-16
      • 2011-04-30
      相关资源
      最近更新 更多