如何在 Django 中保留白色 Space 和换行符?

How to Preserve White Space and line breaks in Django?

我正在制作一个要显示用户代码的项目。我正在使用 Django 的表单。但是当我 post 该表格时,该表格不会保留白色 space 并且换行符。

你能帮帮我吗?

# this is my form

class VigenereCipherDiscussForm(forms.ModelForm):
    class Meta:
        model = VigenereCipherDiscuss
        fields = ['text', 'share']

        widgets = {
            "text": forms.Textarea(attrs={"class":"form-control", "rows":4}),
            "share": forms.Textarea(attrs={"class":"form-control", "rows":5, "placeholder": "Put in your cipher text or code in here to share with others"})
        }

# (Whosebug preserves the line breaks, the "class Meta" is indented nicely)

如果我有这个代码:

x = 2
if x == 2:
    return "2"
else:
    return None

# I want this code to be outputted in the form the way it is right now!

但是 django 给了我

x=2 if x==2: return "2" else return None

使用linebreak

将您的代码更改为:

x=2\nif x==2:\nreturn "2"\nelse:\nreturn None

并在模板中:

{{ value|linebreaks }}

您可以使用 tinymce 创建用户的 code.it 并将其保存在 html 中。 在你的 .html 添加这个:{{ value|linebreaks|safe }} tinymce是这样的: