
04/11/2024
By default, Django uses a built-in user model that includes basic fields like username, password, email, and more. However, you may want to extend this functionality by adding additional fields or modifying existing behaviors (like using an email for authentication). This is where a custom user model comes into play.
Define Your Custom User Model
Open your Django application and navigate to your models.py file. Here, you can define a new user model that subclasses AbstractBaseUser or AbstractUser. The former provides a blank slate, while the latter gives you the standard fields and functionality.
from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): bio = models.TextField(blank=True, null=True)
location = models.CharField(max_length=30, blank=True, null=True)
#### Step 2: Update Settings
2. **Update Your Settings**
After creating your custom user model, you need to tell Django about it. In your `settings.py`, add the following line:
```python
AUTH_USER_MODEL = 'yourapp.CustomUser'
Replace yourapp with the name of the Django app where your CustomUser model is defined.
Create Migrations
After defining your model and updating the settings, you need to create migrations to apply the changes to your database. Run the following command:
python manage.py makemigrations yourapp
Apply Migrations
Once you've created the migrations, apply them using:
python manage.py migrate
Custom Manager
If you need specific query capabilities on your custom user model, consider creating a custom manager. For example:
from django.contrib.auth.models import BaseUserManager class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError("The Email field must be set") email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(email, password, **extra_fields)
And make sure to set this manager in your CustomUser model:
class CustomUser(AbstractUser): objects = CustomUserManager()
#### Step 5: Admin Registration
6. **Registering in Admin**
If you wish to manage the custom user model from the Django admin interface, you need to register it. Create or modify your admin.py file as follows:
```python
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import CustomUser
class CustomUserAdmin(UserAdmin):
model = CustomUser
list_display = ['email', 'username', 'is_staff', 'is_active']
admin.site.register(CustomUser, CustomUserAdmin)
Custom User Forms
If you need to create forms to handle user creation or update, you can extend Django's built-in forms to integrate seamlessly with your custom user model:
from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ('email', 'username') class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ('email', 'username')
By following the aforementioned steps, you can successfully implement a custom user model in Django that meets the unique demands of your application. Remember, as you work with user authentication, to validate and test extensively to ensure that data integrity and security are maintained.
04/11/2024 | Python
04/11/2024 | Python
04/11/2024 | Python
04/11/2024 | Python
04/11/2024 | Python
04/11/2024 | Python
03/11/2024 | Python