Django returning bad help text in my signup page

2019-03-04 06:35发布

问题:

As you can see the help text is not being rendered as UL instead its just plain text Here is my code Forms.py:

class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = CustomUser
        now = datetime.datetime.now()
        fields = ('username', 'email', 'gender', 'security_question', 'answer', 'birth_date', 'resume')
        widgets={
            'birth_date' :DatePickerInput(
                options={
                    'maxDate':str(datetime.datetime.now()),
                }
            )
        }

Views.py:

class SignUp(generic.CreateView):
    form_class = CustomUserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'users/signup.html'

signup.html:

{% extends 'base.html' %}


{% block title %}Sign Up{% endblock %}

{% block content %}
<div class="login-page">
  <h1>Sign up</h1>
    <form method="post" enctype="multipart/form-data">
    {% csrf_token %}
<!--
    {{ form.as_p }}
-->
        <div class="form">
            {% for field in form %}
                <p>
                    {{ field.label_tag }}<br>
                    {{ field }}
                    {% if field.help_text %}
                        <small style="color: grey">{{ field.help_text }}</small>
                    {% endif %}
                     {% for error in field.errors %}
                         <p style="color: red">{{ error }}</p>
                      {% endfor %}
                </p>
            {% endfor %}


            <button type="submit">Sign up</button>
        </div>
    </form>
</div>
{% endblock %}

Can someone help me figure out how do i Fix the issue ? i am using Django2.0.6

回答1:

help_text is allowed to contain HTML - but you are rendering it as a safe string - you need to use the safe template filter to allow the HTML to be rendered.

You are also rendering it inside a <small> tag which will result in invalid HTML if the help text contains a list, as it does in this case.

I'd suggest you consider refactoring your template do handle this - e.g.:

{% if field.help_text %}
    <div style="color: grey">{{ field.help_text|safe }}</div>
{% endif %}

You might also want to consider using styled classes instead of inline styling for these elements.

If you don't want HTML to appear in the help_text then you will need to modify the help_text of the field in question.