Hi everyone !
I’m currently trying to understand how a User ModelForm can work by writing both the model and the form myself.
Here is my code :
models.py
from django.db import models
class UserModel(models.Model):
username = models.CharField(max_length=20)
email = models.CharField(max_length=20)
password1 = models.CharField(max_length=20)
password2 = models.CharField(max_length=20)
forms.py
from django.forms import ModelForm
from django.forms.widgets import PasswordInput
from .models import UserModel
class UserModelForm(ModelForm):
class Meta:
model = UserModel
fields = [
"username",
"email",
"password1",
"password2",
]
widgets = {
"password1":PasswordInput(),
"password2":PasswordInput(),
}
views.py
from django.shortcuts import render
from .forms import UserModelForm
def signupUser(request):
if request.method == "POST":
form = UserModelForm(request.POST)
if form.is_valid():
form.save()
else:
print(form.errors)
else:
form = UserModelForm()
template_name = "accounts/signup.html"
context = {
"form":form,
}
return render(request, template_name, context)
signup.html
{% extends "base.html" %}
{% block page_title %}{% endblock %}
{% block page_content %}
<form id="signupForm" action="accounts:signupUser" method="POST">
{% csrf_token %}
{{ form.username.label }}
{{ form.username }}
{{ form.email.label }}
{{ form.email }}
{{ form.password1.label }}
{{ form.password1 }}
{{ form.password2.label }}
{{ form.password2 }}
<input value ="Sign Up" type="submit">
</form>
{% endblock %}
What I want to achieve is basically validating the form after the “Sign Up” button has been pressed and then save it in my DB.
As I intend to create my own model and form, I have to explicitely code it, do you have a clue on how I could do it my self ? (Checking passwords, cleaning fields, saving)
Best Regards