Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing User Center Features with Django REST Framework and Vue

Tech May 17 3

Automatic API Documentation Generation in DRF

(1) URL Configuration

# Generate documentation with custom title
path('docs', include_docs_urls(title='Journey to the West')),

Accessing http://127.0.0.1:8000/docs generates the API documentation automatically.

(2) Benefits of DRF Documentation

  • Automatically generated
  • Interactive testing capabilities within the docs
  • Code snippets for JavaScript, Shell, and Python

(3) Comment Format in Code

ViewSet comment style, see official documentation for more details:

class GoodsListViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    '''
    list:
        Product list with pagination, search, filtering, and sorting
    retrieve:
        Retrieve product details
    '''

(4) Field Descriptions

Three ways to describe fields in code:

  • Add help_text='description' to model fields
  • Add help_text='description' to serializer fields
  • Add help_text='description' to filters

Dynamic Serializer and Permission Handling for User Information

Since registration and retrieving user details use different serializers, dynamic assignment is needed.

User Detail Endpoint

(1) User Detail Serializer

users/serializers.py

class UserDetailSerializer(serializers.ModelSerializer):
    """
    User detail
    """
    class Meta:
        model = User
        fields = ('name', 'gender', 'birthday', 'email', 'mobile')

(2) View Implementation

users/views.py

from .serializers import UserRegSerializer

from rest_framework import mixins
from rest_framework import authentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.serializers import jwt_encode_handler, jwt_payload_handler
from rest_framework import permissions
from .serializers import UserDetailSerializer


class UserViewset(CreateModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    '''
    User
    '''
    serializer_class = UserRegSerializer
    queryset = User.objects.all()
    authentication_classes = (JSONWebTokenAuthentication, authentication.SessionAuthentication)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = self.perform_create(serializer)
        re_dict = serializer.data
        payload = jwt_payload_handler(user)
        re_dict['token'] = jwt_encode_handler(payload)
        re_dict['name'] = user.name if user.name else user.username

        headers = self.get_success_headers(serializer.data)
        return Response(re_dict, status=status.HTTP_201_CREATED, headers=headers)

    def get_permissions(self):
        if self.action == 'retrieve':
            return [permissions.IsAuthenticated()]
        elif self.action == 'create':
            return []
        return []

    def get_serializer_class(self):
        if self.action == 'retrieve':
            return UserDetailSerializer
        elif self.action == 'create':
            return UserRegSerializer
        return UserDetailSerializer

    def get_object(self):
        return self.request.user

    def perform_create(self, serializer):
        return serializer.save()

Key additions:

  • Inherits mixins.RetrieveModelMixin for user data retrieval
  • Overrides get_object() to fetch the logged-in user
  • Uses get_permissions() with self.action for dynamic permission control
  • Implements get_serializer_class() for dynamic serializer selection

User Profile Update

To allow profile updates, extend with mixins.UpdateModelMixin:

class UserViewset(CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet):

User Favorites Management

(1) Favorite Item Details

Add to user_operation/serializers.py:

class UserFavDetailSerializer(serializers.ModelSerializer):
    '''
    User favorite details
    '''
    
    # Nested serialization of product details via ID
    goods = GoodsSerializer()
    
    class Meta:
        model = UserFav
        fields = ('goods', 'id')

(2) View Implementation

In user_operation/views.py:

class UserFavViewset(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin):
    '''
    User favorites
    '''
    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    lookup_field = 'goods_id'

    def get_queryset(self):
        return UserFav.objects.filter(user=self.request.user)

    def get_serializer_class(self):
        if self.action == 'list':
            return UserFavDetailSerializer
        elif self.action == 'create':
            return UserFavSerializer
        return UserFavSerializer

Users can now view their favorites and remove items.

User Messages Functionality

(1) Message Serializer

In user_operation/serializers.py:

from .models import UserLeavingMessage

class LeavingMessageSerializer(serializers.ModelSerializer):
    '''
    User messages
    '''
    
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )
    
    add_time = serializers.DateTimeField(read_only=True, format='%Y-%m-%d %H:%M')
    
    class Meta:
        model = UserLeavingMessage
        fields = ('user', 'message_type', 'subject', 'message', 'file', 'id', 'add_time')

(2) View Implementation

In user_operation/views.py:

from .serializers import LeavingMessageSerializer
from .models import UserLeavingMessage

class LeavingMessageViewset(mixins.ListModelMixin, mixins.DestroyModelMixin, mixins.CreateModelMixin,
                            viewsets.GenericViewSet):
    '''
    list:
        Get user messages
    create:
        Add message
    delete:
        Delete message
    '''
    
    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = LeavingMessageSerializer

    def get_queryset(self):
        return UserLeavingMessage.objects.filter(user=self.request.user)

(3) URL Configuration

# Register user messages endpoint
router.register(r'messages', LeavingMessageViewset, base_name='messages')

Enables listing and deleting messages.

User Address Management

(1) Address Serializer

In user_operation/serializers.py:

from .models import UserAddress
class AddressSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )
    add_time = serializers.DateTimeField(read_only=True, format='%Y-%m-%d %H:%M')
    
    class Meta:
        model = UserAddress
        fields = ('id', 'user', 'province', 'city', 'district', 'address', 'signer_name', 'add_time', 'signer_mobile')

(2) View Implementation

To support full CRUD operations, inherit from ModelViewSet:

from .serializers import AddressSerializer, UserAddress

class AddressViewset(viewsets.ModelViewSet):
    '''
    Address management
    list:
        Get addresses
    create:
        Add address
    update:
        Update address
    delete:
        Delete address
    '''
    
    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = AddressSerializer

    def get_queryset(self):
        return UserAddress.objects.filter(user=self.request.user)

(3) URL Configuration

# Register address endpoint
router.register(r'address', AddressViewset, base_name='address')
Tags: Django

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.