首页 > 解决方案 > How to Preserve White Space and line breaks in Django?

问题描述

I am making a project where I want to display a user's code. I am using Django's forms. But when I post that form, the form doesn't preserve the white space and the line breaks.

Can you please help me?

# 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"})
        }

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

If i have this code:

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!

But django gives me

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

标签: cssdjangoformsstyling

解决方案


Use linebreak

change your code to:

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

and in template:

{{ value|linebreaks }}

推荐阅读