Home > other >  Paragraphs get lost when posting a form
Paragraphs get lost when posting a form

Time:03-04

Hey, I'm creating a forum using django. When a user posts a thread the written text (in the input field {{obj.content}}) by the user should be displayed exactly as he typed it in. The text is displayed through {{form.content}}.

That means the paragraphs which were made by the user should be maintained. But in the moment they get lost and the text is displayed without paragraphs.

create_thread.py (on this page a thread can be created):

{% extends "forum/index.html" %}
{% load static %}

{% block title %} {{post.title}} {% endblock %}

{% block content %}

    {% for obj in objects %}
    <div >
        <div >{{obj.username}}</div>
        <div >{{obj.topic}}</div>
        <div >{{obj.content}}</div>
    </div>
    {% endfor %}

{% endblock %}

thread.html (on this page the thread is displayed):

<div >
    <h2 >Create a thread</h2>   
    <form method="POST" action="">
        {% csrf_token %}
        <label >Topic</label>
        {{form.topic}}
        <label >Title</label>
        {{form.title}}
        <label >Content</label>
        {{form.content}}
        <button  id="submit-create-thread" type="submit" value="submit">Submit</button>
    </form>
</div>

CodePudding user response:

@md2perpe isn't wrong but perhaps a more concise answer would be:

{{ form.content|linebreaks }}

CodePudding user response:

The paragraphs are probably not lost. What is happening is that line breaks in text inside HTML are not shown as line breaks when rendered on the page.

You need to replace line breaks with <br>. You should also replace < with &lt; and > with &gt;. Otherwise your page will be vulnerable to script injection.

You can test it now: enter <script>window.alert('hello')</script> into the form and see what happens when you submit the form.

  • Related