I'm trying to add a registration page to my Django project and I have made the registration form in the forms.py file.
class createUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
widgets = {
'username' : forms.TextInput(attrs={'class':'form-control form-input','placeholder':'Username...'}),
'email' : forms.EmailInput(attrs={'class':'form-control form-input','placeholder':'Email...'}),
'password1' : forms.PasswordInput(attrs={'class':'form-control form-input','placeholder':'Password'}),
'password2' : forms.PasswordInput(attrs={'class':'form-control form-input','placeholder':'Re-type password'}),
}
HTML
<h4>Sign in</h4>
<div class="form-container">
<form method="POST" action="">
<div class="form-render" style="display: block;">
{% csrf_token %}
<div style="margin-bottom: 1rem;">
{{form.username}}
</div>
<div style="margin-bottom: 1rem;">
{{form.email}}
</div>
<div style="margin-bottom: 1rem;">
{{form.password1}}
</div>
<div style="margin-bottom: 1rem;">
{{form.password2}}
</div>
<button type="submit" class="btn btn-primary" style="border-radius: 0px; outline-color: #167896; background-color:#167896; width: 15rem; margin-left: 1.5rem;">Submit</button>
</div>
</form>
<div style="display: flex; margin-left: 1.75rem; margin-top: 1rem; margin-bottom: 0rem;">
<p>Already have an account?</p><a style="text-decoration: none; " class="forgot" href="{% url 'login' %}">  Log in</a>
</div>
</div>
After rendering out HTML, bootstrap styles are not added to the password input fields. This is the screenshot of my output page.
There are several ways to skin this cat, but my preferred method is to use the django-bootstrap4 package: https://pypi.org/project/django-bootstrap4/
venv: pip install django-bootstrap4INSTALLED_APPS:INSTALLED_APPS = (
# ...
"bootstrap4",
# ...
)
{% load bootstrap4 %}
<h4>Sign in</h4>
<div class="form-container">
<form method="POST" action="">
{% csrf_token %}
{% bootstrap_form form %}
<button type="submit" class="btn btn-primary">Submit</button>
</div>
It will automatically take care of displaying errors properly. If you need to do any custom actions for fields, you can also loop through the fields:
{% load bootstrap4 %}
<h4>Sign in</h4>
<div class="form-container">
<form method="POST" action="">
{% csrf_token %}
{% for field in form %}
{% bootstrap_field field %}
{% endfor %}
<button type="submit" class="btn btn-primary">Submit</button>
</div>
Good luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With