Issue
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 class="mb-4" src="{% static 'images/logo.jpg' %}" alt="" width="100" height="100">
<h1 class="h3 mb-3 fw-normal">Please sign in</h1>
<div class="form-floating">
<input type="text" class="form-control" id="floatingInput" placeholder="[email protected]"
value="{{form.username}}">
<label for="floatingInput">Username</label>
</div>
<div class="form-floating">
<input type="password" class="form-control" id="floatingPassword" placeholder="Password"
value="{{form.password}}">
<label for="floatingPassword">Password</label>
</div>
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"> Remember me   <a href="{% url 'password_reset' %}">
Lost password?</a>
</label>
</div>
<button class="w-100 btn btn-lg btn-primary" type="submit">Sign in</button>
<p class="mt-5 mb-3 text-muted">© 2022 all rights deserved</p>
</form>
Solution
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.
Answered By - vinkomlacic
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.