viewset CRUD in django
CRUD with viewset
Views.py
from django.shortcuts import render from rest_framework.viewsets import ModelViewSet from core.models import User from .serializers import * from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from rest_framework_simplejwt.authentication import JWTAuthentication from .permissions import *
class AccountView(ModelViewSet): queryset = User.objects.all() serializer_class = AccountSerializer permission_classes = [IsAuthenticated, isManager] authentication_classes = [JWTAuthentication] # Allow only GET, PUT and POST methods http_method_names = ["GET","PUT","POST"] |
Urls.py
from .views import * from rest_framework.routers import SimpleRouter
router = SimpleRouter() router.register("",AccountView) urlpatterns = [] urlpatterns = urlpatterns + router.urls |
Serializers.py
from rest_framework import serializers from core.models import User
class AccountSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ "first_name", "last_name", "email", "password", "address", "is_manager", ] extra_kwargs = {"password": {"write_only": True}}
def create(self, validated_data): # Hash the password before saving the user password = validated_data.pop("password", None) instance = super(AccountSerializer, self).create(validated_data) if password is not None: instance.set_password(password) instance.save() return instance
def update(self, instance, validated_data): # Handle password update separately password = validated_data.pop("password", None) # Update other fields instance = super(AccountSerializer, self).update(instance, validated_data) # Update the password if provided if password is not None: instance.set_password(password) instance.save() return instance |
Baseapp/urls.py
from django.urls import path, include from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView from account.urls import *
from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, )
urlpatterns = [ path("account/",include("account.urls")), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] |
Baseapp/models.py
from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from .manager import *
class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=15) last_name = models.CharField(max_length=15) email = models.EmailField(max_length=200, unique=True) address = models.TextField(null=True) is_manager = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name"]
def __str__(self): return self.email |
Manager.py
from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin, )
class UserManager(BaseUserManager): def create_user(self, email, password, **extra_args): user = self.model(email=self.normalize_email(email), **extra_args) user.set_password(password) user.save(using=self._db) return user
def create_superuser(self, email, password, **extra_args): user = self.create_user(email=email, password=password, **extra_args) user.is_manager = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user |
Baseapp/admin.py
from django.contrib import admin
from django.contrib import admin from .models import * from django.contrib.auth.admin import UserAdmin
class UserAdmin(UserAdmin): ordering = ( "email", "id", )
list_display = ( "first_name", "last_name", "email", "is_manager", "is_staff", "is_superuser", "is_active", )
search_fields = ("first_name", "last_name", "email")
list_filter = ("is_staff", "is_active")
# list_editable = ("is_staff", "is_superuser", "is_active")
exclude = ("username", "date_joined")
add_fieldsets = ( ("Personal Info", {"fields": ("first_name", "last_name")}), ( "Contact Info", { "fields": ( "email", "address", ), }, ), ( "Password", { "fields": ( "password1", "password2", ), }, ), )
fieldsets = ( ( "Contact Info", { "fields": ( "email", "address", ) }, ), ( "Personal Info", { "fields": ( "first_name", "last_name", ), "classes": ["wide", "extrapretty"], }, ), ( "Permissions", { "fields": ( "is_active", "is_staff", "is_superuser", "groups", ) }, ), ("Password", {"fields": ("password",)}), )
admin.site.register(User, UserAdmin) |
github: iamshimantadas/django-code-examples (github.com)