Home > Net >  Problem with placeholder on a django template input form field
Problem with placeholder on a django template input form field

Time:03-05

I am creating a user login using the default django authentication system.

Using a bootstrap template, I am creating a form with custom fields, and they are working correctly.

The problem is that when displaying this form, it renders showing the value attribute instead of the placeholder that I have passed to it.

This is who it looks: login page

login.html

    <form method="post" action="{% url 'login' %}"> {% csrf_token %}
      <img  src="{% static 'images/logo.jpg' %}" alt="" width="100" height="100">
      <h1 >Please sign in</h1>

      <div >
        <input type="text"  id="floatingInput" placeholder="[email protected]"
          value="{{form.username}}">
        <label for="floatingInput">Username</label>
      </div>
      <div >
        <input type="password"  id="floatingPassword" placeholder="Password"
          value="{{form.password}}">
        <label for="floatingPassword">Password</label>
      </div>

      <div >
        <label>
          <input type="checkbox" value="remember-me"> Remember me &emsp; <a href="{% url 'password_reset' %}">
            Lost password?</a>
        </label>
      </div>
      <button  type="submit">Sign in</button>
      <p >&copy; 2022 all rights deserved</p>
    </form>

CodePudding user response:

When using {{ form.username }} you are sending the str(form.username) to the value attribute. The __str__ method of the form field renders the HTML. That is why you're seeing what you're seeing.

To fix this, you could put {{ form.username.initial }} to display the initial value of the field.

Tip: try using crispy forms for rendering forms. It is way easier and makes a more compact syntax which depends on the form code, not on the HTML. See https://django-crispy-forms.readthedocs.io/en/latest/

Another thing, I think you're missing the name attribute on the input fields. Not sure if this works without it.

  • Related