Can you please check if i done "register" function correctly in django

i am new in django , can you please check if I done "register" function in the correct way , without applying djang1o forms because i find difficult to do it , so i choose this way [enter image description here]

Please do not write custom logic to create model objects. For example in the view you are here using, you do not check if the items appear in the request.POST data, furthermore you will create a Customers object, even if later that username turns out to be used. It thus makes the logic harder, and the the view less robust.

It is also not entirely clear to me why you repeat data in both the Customer and the User, this introduces data duplicate. If later a user chainges their email, then you will need to update both the User and the Customer, which makes the views more complicated. Usually one uses a ForeignKey for this to refer to the user. The default user model even has a first_name and last_name field, so your Customers model does not add that much extra information. So you can model the user with:

from django.conf import settings

class Customer(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
    )

Then we can subclass the CreateUserForm, and add the first_name, last_name and email fields:

# app_name/forms.py

from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm

class CustomCreateUserForm(UserCreationForm):
    class Meta:
        model = get_user_model()
        fields = ('username', 'email', 'first_name', 'last_name')

Then in the view, we can fix work with this form:

from app_name.forms import CustomCreateUserForm

def register(request):
    if request.method == 'POST':
        form = CustomUserCreateForm(request.POST)
        if form.is_valid():
            user = form.save()
            Customer.objects.create(user=user)
            return redirect('login_user')
    elif 'password2' in form.errors:
        messages.info(request, 'Both passwords are not matching')
    elif 'username' in form.errors:
        messages.info(request, 'Username is already taken')
    elif 'email' in form.errors:
        messages.info(request, 'Email is already taken')
    return render(request, 'compte/register.html')

In the HTML form you then use password2 instead of repassword, and first_name and last_name instead of fname and lname. The form will also validate that the email address is for example a valid email adress, and not just / or !.

Back to Top