htmlcssdjangodjango-widget-tweaks

How to customize django signup form's helper texts with widget_tweaks?


I am trying to create a signup page and using django's default signup form while trying it. I have a problem with Password field's helper text because I cannot fix it.

Here is my signup.html's body;

<body class="text-center">
    <form class="form-signin" method="POST">
      {% csrf_token %}
      <h1 class="h3 mb-3 font-weight-normal">Sign up</h1>
      {% for field in form %}
        <label for="{{ field.id_for_label_tag }}">{{ field.label_tag }}</label>
        {{ field | add_class:'form-control' }}
        {% for text in field %}
          <small style="color: grey">{{ field.help_text }}</small></br></br>
        {% endfor %}
        {% for error in field.errors %}
          <p style="color: red">{{ error }}</p>
        {% endfor %}
      {% endfor %}
      <button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>
      <p class="mt-5 mb-3 text-muted">&copy; 2017-2018</p>
    </form>
</body>

Here is the page's screen shot; Signup page screen shot

This is also another link for screen shot (if you cannot open the above one): https://prnt.sc/kcsmaf

As I show on the screen shot with red arrow, there is a problem with ul and li tags. They aren't affected with the style. How can I fix it?


Solution

  • By default Django escapes the content of variables. For example <li> as string is rendered as &lt;li&gt;. This is frequently desired behavior: imagine that a user writes a comment like 'o(><)o', then you probably do not want to interpret this as HTML, since it can mean that a browser can no longer parse the rest of the document.

    You can however mark a variable such that it is not escaped with the safe [Django-doc] template filter:

    <body class="text-center">
        <form class="form-signin" method="POST">
          {% csrf_token %}
          <h1 class="h3 mb-3 font-weight-normal">Sign up</h1>
          {% for field in form %}
            <label for="{{ field.id_for_label_tag }}">{{ field.label_tag }}</label>
            {{ field | add_class:'form-control' }}
            {% for text in field %}
              <small style="color: grey">{{ field.help_text|safe }}</small></br></br>
            {% endfor %}
            {% for error in field.errors %}
              <p style="color: red">{{ error }}</p>
            {% endfor %}
          {% endfor %}
          <button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>
          <p class="mt-5 mb-3 text-muted">© 2017-2018</p>
        </form>
    </body>

    In that case, if help_text for example contains a <li> it will be rendered as HTML, and thus the browser can render this as a list.

    Note however that if you mark something as safe, then you are responsible for the fact that it contains valid HTML, and thus for example a tag is closed appropriately, etc.