Here is my custom code for handling user sign-up in Django:
class SignUpForm(forms.ModelForm):
name = forms.CharField(label="name", required=True, widget=forms.TextInput())
email = forms.CharField(label="email", required=True, widget=forms.TextInput())
password = forms.CharField(label="password", widget=forms.PasswordInput(), required=True)
confirm_password = forms.CharField(label="confirm_password", widget=forms.PasswordInput(), required=True)
def clean(self):
cleaned_data = super(SignUpForm, self).clean()
password = cleaned_data.get("password")
confirm_password = cleaned_data.get("confirm_password")
if password != confirm_password:
self.add_error('confirm_password', "Password and confirm password do not match")
return cleaned_data
class Meta:
model = get_user_model()
fields = ('name', 'email', 'password')
This is how I have structured the signup form in my HTML file:
{% block content %}
<form method="post">
<div class="sign-card">
<h3>Signup</h3>
{% csrf_token %}
<div class="input-div">
<label for="{{ form.name.id_for_label }}">Username:</label>
{{ form.name }}
</div>
<div class="input-div">
<label for="{{ form.email.id_for_label }}">Email:</label>
{{ form.email }}
</div>
<div class="input-div">
<label for="{{ form.password.id_for_label }}">Password:</label>
{{ form.password }}
</div>
<div class="input-div">
<label for="{{ form.confirm_password.id_for_label }}">Confirm Password:</label>
{{ form.confirm_password }}
</div>
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% endif %}
<button type="submit" class="btn">Sign up</button>
<p>Already have an account? <a href="{% url 'login' %}">Log In</a></p>
</div>
</form>
{% endblock %}
My view function for processing the signup form submission looks like this:
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('name')
password = form.cleaned_data.get('password')
email = form.cleaned_data.get('email')
user = authenticate(username=username, password=password, email=email)
login(request, user)
return redirect('index')
else:
form = SignUpForm()
return render(request, 'registration/signup.html', {'form': form})
I am currently facing an issue with styling the error messages in my HTML without using CSS. I don't want to use Django messages or modify my views.py. Can anyone suggest a solution to style the error messages appropriately within the existing setup?
Thank you for your help.