Django Rest Framework注册及自定义User模型技术咨询
Got it, let's walk through how to set up user registration with your custom User model in Django Rest Framework. I'll break this down step by step so it's easy to follow.
First, we need a serializer to validate incoming registration data (like email, phone, password) and convert it into a User instance. Since your model uses email as the primary identifier, we’ll make sure the serializer handles that correctly, plus mark the password as write-only so it never gets exposed in responses.
Add this to your app's serializers.py:
from rest_framework import serializers from .models import User class RegisterSerializer(serializers.ModelSerializer): # Password is write-only to prevent it from being returned in API responses password = serializers.CharField(write_only=True, required=True) class Meta: model = User # Include fields users will submit during registration fields = ('email', 'phone', 'password', 'is_pro') # Optional: Set default for is_pro if you don't want users to set it during sign-up extra_kwargs = {'is_pro': {'default': False}} def create(self, validated_data): # Use your custom UserManager to create the user (this handles password hashing) user = User.objects.create_user( email=validated_data['email'], phone=validated_data['phone'], password=validated_data['password'], is_pro=validated_data.get('is_pro', False) ) return user
Next, we’ll create a view to handle the registration POST request. Using DRF’s CreateAPIView keeps things clean—it handles most of the boilerplate for creating objects, and we can customize the response to include useful data like the user’s token (from your model’s token property).
Add this to your app's views.py:
from rest_framework import generics from rest_framework.response import Response from rest_framework.status import HTTP_201_CREATED from .serializers import RegisterSerializer class RegistrationView(generics.CreateAPIView): serializer_class = RegisterSerializer def create(self, request, *args, **kwargs): # Validate incoming data serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) # Create the user instance user = serializer.save() # Build a custom response with user details and their token response_data = { 'email': user.email, 'phone': user.phone, 'is_pro': user.is_pro, 'token': user.token # Leverage your model's token property here } return Response(response_data, status=HTTP_201_CREATED)
Now map the view to a URL so users can access the registration endpoint. Add this to your app's urls.py:
from django.urls import path from .views import RegistrationView urlpatterns = [ path('register/', RegistrationView.as_view(), name='user-registration'), # Add other app URLs here as needed ]
Before testing, make sure you’ve covered these key details:
- Implement Custom UserManager: Your
Usermodel referencesUserManager(), so you need to define this manager properly to handle user creation. Add this to your app'smodels.py:from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, phone, 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, phone=phone, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, phone, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError("Superuser must have is_staff=True") if extra_fields.get('is_superuser') is not True: raise ValueError("Superuser must have is_superuser=True") return self.create_user(email, phone, password, **extra_fields) - Set AUTH_USER_MODEL: In your project's
settings.py, tell Django to use your custom user model:AUTH_USER_MODEL = 'your_app_name.User'
You can test the registration endpoint using tools like Postman, curl, or DRF’s built-in browsable API:
- Send a POST request to
http://your-domain/register/ - Include a JSON body like this:
{ "email": "user@example.com", "phone": "1234567890", "password": "your_secure_password", "is_pro": false } - You should get a 201 Created response with the user’s details and their authentication token.
内容的提问来源于stack exchange,提问作者Jekson

