Creating a custom new user django

To create a custom new user form in Django, you can follow these steps:

Step 1: Create a new model

In your Django project, create a new file called models.py in your app directory (e.g. myapp/models.py). In this file, define a new model that inherits from AbstractBaseUser and PermissionsMixin:

from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.db import models

class CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True)
    username = models.CharField(max_length=255, unique=True)
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username', 'first_name', 'last_name']

    def __str__(self):
        return self.email

In this example, we're creating a custom user model with additional fields for first_name and last_name. We're also setting email as the username field and requiring username, first_name, and last_name as required fields.

Step 2: Create a custom user form

Create a new file called forms.py in your app directory (e.g. myapp/forms.py). In this file, define a new form that inherits from forms.ModelForm:

from django import forms
from.models import CustomUser

class CustomUserForm(forms.ModelForm):
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput)

    class Meta:
        model = CustomUser
        fields = ('email', 'username', 'first_name', 'last_name')

    def clean_password2(self):
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')
        if password1 and password2 and password1!= password2:
            raise forms.ValidationError('Passwords do not match')
        return password2

In this example, we're creating a custom form that includes fields for password1 and password2 to validate the password and confirm password fields. We're also overriding the clean_password2 method to check if the passwords match.

Step 3: Create a view

Create a new file called views.py in your app directory (e.g. myapp/views.py). In this file, define a new view that handles the creation of a new user:

from django.shortcuts import render, redirect
from.forms import CustomUserForm
from.models import CustomUser

def create_user(request):
    if request.method == 'POST':
        form = CustomUserForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('login')
    else:
        form = CustomUserForm()
    return render(request, 'register.html', {'form': form})

In this example, we're creating a view that handles the creation of a new user. If the request is a POST request, we're creating a new instance of the CustomUserForm and checking if it's valid. If it's valid, we're saving the form and redirecting the user to the login page. If the request is not a POST request, we're creating a new instance of the CustomUserForm and rendering the registration form.

Step 4: Create a template

Create a new file called register.html in your app directory (e.g. myapp/templates/myapp/register.html). In this file, define the HTML template for the registration form:

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Register</button>
</form>

In this example, we're creating a simple HTML form that includes the fields from the CustomUserForm. We're also including a CSRF token to prevent cross-site request forgery attacks.

Step 5: Add the view to the URLconf

In your app's urls.py file, add a new URL pattern that maps to the create_user view:

from django.urls import path
from. import views

urlpatterns = [
    path('register/', views.create_user, name='register'),
]

In this example, we're adding a new URL pattern that maps to the create_user view. The URL pattern is /register/, and the view is named register.

That's it! With these steps, you've created a custom new user form in Django. When a user submits the form, the create_user view will create a new instance of the CustomUser model and save it to the database.