├── .gitignore ├── CRUD API using Class Based View └── api │ ├── api │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py │ ├── app │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── serializer.py │ ├── tests.py │ └── views.py │ ├── db.sqlite3 │ └── manage.py ├── CRUD API using Function Based View └── api │ ├── api │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ ├── settings.cpython-38.pyc │ │ ├── urls.cpython-38.pyc │ │ └── wsgi.cpython-38.pyc │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py │ ├── app │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ ├── admin.cpython-38.pyc │ │ ├── apps.cpython-38.pyc │ │ └── models.cpython-38.pyc │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── __init__.py │ │ └── __pycache__ │ │ │ └── __init__.cpython-38.pyc │ ├── models.py │ ├── serializer.py │ ├── tests.py │ ├── urls.py │ └── views.py │ ├── db.sqlite3 │ └── manage.py ├── Class Based API View (CRUD) └── api │ ├── api │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py │ ├── app │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── serializer.py │ ├── tests.py │ └── views.py │ ├── db.sqlite3 │ └── manage.py ├── Concrete View Class Part-I └── api │ ├── api │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py │ ├── app │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── serializer.py │ ├── tests.py │ └── views.py │ ├── db.sqlite3 │ └── manage.py ├── Concrete View Class Part-II └── api │ ├── api │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py │ ├── app │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── serializer.py │ ├── tests.py │ └── views.py │ ├── db.sqlite3 │ └── manage.py ├── Function Based API View (CRUD) └── api │ ├── api │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py │ ├── app │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── serializer.py │ ├── tests.py │ └── views.py │ ├── db.sqlite3 │ └── manage.py ├── Generic API View and Mixins (CRUD) └── api │ ├── api │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py │ ├── app │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── serializer.py │ ├── tests.py │ └── views.py │ ├── db.sqlite3 │ └── manage.py ├── Model Serializer in Django (CRUD) └── api │ ├── api │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py │ ├── app │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── serializer.py │ ├── tests.py │ └── views.py │ ├── db.sqlite3 │ └── manage.py ├── README.md └── third_part_app.py /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.toptal.com/developers/gitignore/api/python,django,visualstudiocode,windows 3 | # Edit at https://www.toptal.com/developers/gitignore?templates=python,django,visualstudiocode,windows 4 | 5 | ### Django ### 6 | *.log 7 | *.pot 8 | *.pyc 9 | __pycache__/ 10 | local_settings.py 11 | media 12 | 13 | # If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/ 14 | # in your Git repository. Update and uncomment the following line accordingly. 15 | # /staticfiles/ 16 | 17 | ### Django.Python Stack ### 18 | # Byte-compiled / optimized / DLL files 19 | *.py[cod] 20 | *$py.class 21 | 22 | # C extensions 23 | *.so 24 | 25 | # Distribution / packaging 26 | .Python 27 | build/ 28 | develop-eggs/ 29 | dist/ 30 | downloads/ 31 | eggs/ 32 | .eggs/ 33 | lib/ 34 | lib64/ 35 | parts/ 36 | sdist/ 37 | var/ 38 | wheels/ 39 | share/python-wheels/ 40 | *.egg-info/ 41 | .installed.cfg 42 | *.egg 43 | MANIFEST 44 | 45 | # PyInstaller 46 | # Usually these files are written by a python script from a template 47 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 48 | *.manifest 49 | *.spec 50 | 51 | # Installer logs 52 | pip-log.txt 53 | pip-delete-this-directory.txt 54 | 55 | # Unit test / coverage reports 56 | htmlcov/ 57 | .tox/ 58 | .nox/ 59 | .coverage 60 | .coverage.* 61 | .cache 62 | nosetests.xml 63 | coverage.xml 64 | *.cover 65 | *.py,cover 66 | .hypothesis/ 67 | .pytest_cache/ 68 | cover/ 69 | 70 | # Translations 71 | *.mo 72 | 73 | # Django stuff: 74 | 75 | # Flask stuff: 76 | instance/ 77 | .webassets-cache 78 | 79 | # Scrapy stuff: 80 | .scrapy 81 | 82 | # Sphinx documentation 83 | docs/_build/ 84 | 85 | # PyBuilder 86 | .pybuilder/ 87 | target/ 88 | 89 | # Jupyter Notebook 90 | .ipynb_checkpoints 91 | 92 | # IPython 93 | profile_default/ 94 | ipython_config.py 95 | 96 | # pyenv 97 | # For a library or package, you might want to ignore these files since the code is 98 | # intended to run in multiple environments; otherwise, check them in: 99 | # .python-version 100 | 101 | # pipenv 102 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 103 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 104 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 105 | # install all needed dependencies. 106 | #Pipfile.lock 107 | 108 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 109 | __pypackages__/ 110 | 111 | # Celery stuff 112 | celerybeat-schedule 113 | celerybeat.pid 114 | 115 | # SageMath parsed files 116 | *.sage.py 117 | 118 | # Environments 119 | .env 120 | .venv 121 | env/ 122 | venv/ 123 | ENV/ 124 | env.bak/ 125 | venv.bak/ 126 | 127 | # Spyder project settings 128 | .spyderproject 129 | .spyproject 130 | 131 | # Rope project settings 132 | .ropeproject 133 | 134 | # mkdocs documentation 135 | /site 136 | 137 | # mypy 138 | .mypy_cache/ 139 | .dmypy.json 140 | dmypy.json 141 | 142 | # Pyre type checker 143 | .pyre/ 144 | 145 | # pytype static type analyzer 146 | .pytype/ 147 | 148 | # Cython debug symbols 149 | cython_debug/ 150 | 151 | ### Python ### 152 | # Byte-compiled / optimized / DLL files 153 | 154 | # C extensions 155 | 156 | # Distribution / packaging 157 | 158 | # PyInstaller 159 | # Usually these files are written by a python script from a template 160 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 161 | 162 | # Installer logs 163 | 164 | # Unit test / coverage reports 165 | 166 | # Translations 167 | 168 | # Django stuff: 169 | 170 | # Flask stuff: 171 | 172 | # Scrapy stuff: 173 | 174 | # Sphinx documentation 175 | 176 | # PyBuilder 177 | 178 | # Jupyter Notebook 179 | 180 | # IPython 181 | 182 | # pyenv 183 | # For a library or package, you might want to ignore these files since the code is 184 | # intended to run in multiple environments; otherwise, check them in: 185 | # .python-version 186 | 187 | # pipenv 188 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 189 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 190 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 191 | # install all needed dependencies. 192 | 193 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 194 | 195 | # Celery stuff 196 | 197 | # SageMath parsed files 198 | 199 | # Environments 200 | 201 | # Spyder project settings 202 | 203 | # Rope project settings 204 | 205 | # mkdocs documentation 206 | 207 | # mypy 208 | 209 | # Pyre type checker 210 | 211 | # pytype static type analyzer 212 | 213 | # Cython debug symbols 214 | 215 | ### VisualStudioCode ### 216 | .vscode/* 217 | !.vscode/settings.json 218 | !.vscode/tasks.json 219 | !.vscode/launch.json 220 | !.vscode/extensions.json 221 | *.code-workspace 222 | 223 | # Local History for Visual Studio Code 224 | .history/ 225 | 226 | ### VisualStudioCode Patch ### 227 | # Ignore all local history of files 228 | .history 229 | .ionide 230 | 231 | ### Windows ### 232 | # Windows thumbnail cache files 233 | Thumbs.db 234 | Thumbs.db:encryptable 235 | ehthumbs.db 236 | ehthumbs_vista.db 237 | 238 | # Dump file 239 | *.stackdump 240 | 241 | # Folder config file 242 | [Dd]esktop.ini 243 | 244 | # Recycle Bin used on file shares 245 | $RECYCLE.BIN/ 246 | 247 | # Windows Installer files 248 | *.cab 249 | *.msi 250 | *.msix 251 | *.msm 252 | *.msp 253 | 254 | # Windows shortcuts 255 | *.lnk 256 | 257 | # End of https://www.toptal.com/developers/gitignore/api/python,django,visualstudiocode,windows -------------------------------------------------------------------------------- /CRUD API using Class Based View/api/api/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/CRUD API using Class Based View/api/api/__init__.py -------------------------------------------------------------------------------- /CRUD API using Class Based View/api/api/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for api project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /CRUD API using Class Based View/api/api/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for api project. 3 | 4 | Generated by 'django-admin startproject' using Django 3.2.6. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/3.2/ref/settings/ 11 | """ 12 | 13 | from pathlib import Path 14 | 15 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 16 | BASE_DIR = Path(__file__).resolve().parent.parent 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'django-insecure-si^8pj(=&c^w_t(&j3zm+fu=9hsex^8ky6!3a5ivi7gm#k(nd)' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'app', 41 | 'rest_framework' 42 | ] 43 | 44 | MIDDLEWARE = [ 45 | 'django.middleware.security.SecurityMiddleware', 46 | 'django.contrib.sessions.middleware.SessionMiddleware', 47 | 'django.middleware.common.CommonMiddleware', 48 | 'django.middleware.csrf.CsrfViewMiddleware', 49 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 50 | 'django.contrib.messages.middleware.MessageMiddleware', 51 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 52 | ] 53 | 54 | ROOT_URLCONF = 'api.urls' 55 | 56 | TEMPLATES = [ 57 | { 58 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 59 | 'DIRS': [], 60 | 'APP_DIRS': True, 61 | 'OPTIONS': { 62 | 'context_processors': [ 63 | 'django.template.context_processors.debug', 64 | 'django.template.context_processors.request', 65 | 'django.contrib.auth.context_processors.auth', 66 | 'django.contrib.messages.context_processors.messages', 67 | ], 68 | }, 69 | }, 70 | ] 71 | 72 | WSGI_APPLICATION = 'api.wsgi.application' 73 | 74 | 75 | # Database 76 | # https://docs.djangoproject.com/en/3.2/ref/settings/#databases 77 | 78 | DATABASES = { 79 | 'default': { 80 | 'ENGINE': 'django.db.backends.sqlite3', 81 | 'NAME': BASE_DIR / 'db.sqlite3', 82 | } 83 | } 84 | 85 | 86 | # Password validation 87 | # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators 88 | 89 | AUTH_PASSWORD_VALIDATORS = [ 90 | { 91 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 92 | }, 93 | { 94 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 95 | }, 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 98 | }, 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 101 | }, 102 | ] 103 | 104 | 105 | # Internationalization 106 | # https://docs.djangoproject.com/en/3.2/topics/i18n/ 107 | 108 | LANGUAGE_CODE = 'en-us' 109 | 110 | TIME_ZONE = 'UTC' 111 | 112 | USE_I18N = True 113 | 114 | USE_L10N = True 115 | 116 | USE_TZ = True 117 | 118 | 119 | # Static files (CSS, JavaScript, Images) 120 | # https://docs.djangoproject.com/en/3.2/howto/static-files/ 121 | 122 | STATIC_URL = '/static/' 123 | 124 | # Default primary key field type 125 | # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field 126 | 127 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 128 | -------------------------------------------------------------------------------- /CRUD API using Class Based View/api/api/urls.py: -------------------------------------------------------------------------------- 1 | """api URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/3.2/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path 18 | from app.views import TeacherAPI 19 | urlpatterns = [ 20 | path('admin/', admin.site.urls), 21 | path('api/',TeacherAPI.as_view()) 22 | ] 23 | -------------------------------------------------------------------------------- /CRUD API using Class Based View/api/api/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for api project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /CRUD API using Class Based View/api/app/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/CRUD API using Class Based View/api/app/__init__.py -------------------------------------------------------------------------------- /CRUD API using Class Based View/api/app/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from .models import Teacher 3 | # Register your models here. 4 | 5 | @admin.register(Teacher) 6 | class TeacherAdmin(admin.ModelAdmin): 7 | list_display = ['id','full_name','address','salary'] -------------------------------------------------------------------------------- /CRUD API using Class Based View/api/app/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class AppConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'app' 7 | -------------------------------------------------------------------------------- /CRUD API using Class Based View/api/app/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.2.6 on 2021-09-02 18:26 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | initial = True 9 | 10 | dependencies = [ 11 | ] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name='Teacher', 16 | fields=[ 17 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 18 | ('full_name', models.CharField(max_length=100)), 19 | ('address', models.CharField(max_length=100)), 20 | ('salary', models.BigIntegerField()), 21 | ], 22 | ), 23 | ] 24 | -------------------------------------------------------------------------------- /CRUD API using Class Based View/api/app/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/CRUD API using Class Based View/api/app/migrations/__init__.py -------------------------------------------------------------------------------- /CRUD API using Class Based View/api/app/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | class Teacher(models.Model): 5 | full_name = models.CharField(max_length=100) 6 | address = models.CharField(max_length=100) 7 | salary = models.BigIntegerField() -------------------------------------------------------------------------------- /CRUD API using Class Based View/api/app/serializer.py: -------------------------------------------------------------------------------- 1 | from app.models import Teacher 2 | from rest_framework import serializers 3 | 4 | class TeacherSerializer(serializers.Serializer): 5 | full_name = serializers.CharField(max_length=100) 6 | address = serializers.CharField(max_length=100) 7 | salary = serializers.IntegerField() 8 | def create(self,validated_data): 9 | return Teacher.objects.create(**validated_data) 10 | 11 | def update(self,instance,validated_data): 12 | instance.full_name = validated_data.get('full_name',instance.full_name) 13 | instance.address = validated_data.get('address',instance.address) 14 | instance.salary = validated_data.get('salary',instance.salary) 15 | instance.save() 16 | return instance 17 | 18 | -------------------------------------------------------------------------------- /CRUD API using Class Based View/api/app/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /CRUD API using Class Based View/api/app/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | from django.views import View 3 | from django.views.decorators.csrf import csrf_exempt 4 | from django.utils.decorators import method_decorator 5 | from django.http import JsonResponse 6 | import re 7 | from .serializer import TeacherSerializer 8 | from .models import Teacher 9 | import io 10 | from rest_framework.parsers import JSONParser 11 | # Create your views here. 12 | 13 | @method_decorator(csrf_exempt,name='dispatch') 14 | class TeacherAPI(View): 15 | def get(self,request,*ar,**arg): 16 | stream = io.BytesIO(request.body) 17 | python_data = JSONParser().parse(stream) 18 | id = python_data.get('id') 19 | if id is not None: 20 | get_data = Teacher.objects.get(id= id) 21 | serializer = TeacherSerializer(get_data) 22 | else: 23 | get_data = Teacher.objects.all() 24 | serializer = TeacherSerializer(get_data,many=True) 25 | return JsonResponse({'success':serializer.data}) 26 | 27 | def post(self,request,*arg,**args): 28 | stream = io.BytesIO(request.body) 29 | python_data = JSONParser().parse(stream) 30 | serializer = TeacherSerializer(data = python_data) 31 | if serializer.is_valid(): 32 | serializer.save() 33 | return JsonResponse({'message':'Data is post successfully'}) 34 | else: 35 | return JsonResponse(serializer.errors) 36 | 37 | def put(self,request,*arg,**args): 38 | stream = io.BytesIO(request.body) 39 | python_data = JSONParser().parse(stream) 40 | id = python_data.get('id') 41 | obj = Teacher.objects.get(id = id) 42 | print(obj) 43 | print(obj.full_name) 44 | serializer = TeacherSerializer(obj,data=python_data,partial=True) 45 | if serializer.is_valid(): 46 | serializer.save() 47 | obj = Teacher.objects.get(id = id) 48 | return JsonResponse({'message':'Data is updated successfully!'}) 49 | else: 50 | return JsonResponse(serializer.errors) 51 | 52 | def delete(self,request,*arg,**args): 53 | stream = io.BytesIO(request.body) 54 | python_data = JSONParser().parse(stream) 55 | obj = Teacher.objects.get(id = python_data.get('id')) 56 | if python_data.get('id') is not None: 57 | obj.delete() 58 | return JsonResponse({'Message':'Data is deleted successfully! '}) 59 | else: 60 | return JsonResponse({'Message':'Cannot delete!'}) -------------------------------------------------------------------------------- /CRUD API using Class Based View/api/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/CRUD API using Class Based View/api/db.sqlite3 -------------------------------------------------------------------------------- /CRUD API using Class Based View/api/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /CRUD API using Function Based View/api/api/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/CRUD API using Function Based View/api/api/__init__.py -------------------------------------------------------------------------------- /CRUD API using Function Based View/api/api/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/CRUD API using Function Based View/api/api/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /CRUD API using Function Based View/api/api/__pycache__/settings.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/CRUD API using Function Based View/api/api/__pycache__/settings.cpython-38.pyc -------------------------------------------------------------------------------- /CRUD API using Function Based View/api/api/__pycache__/urls.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/CRUD API using Function Based View/api/api/__pycache__/urls.cpython-38.pyc -------------------------------------------------------------------------------- /CRUD API using Function Based View/api/api/__pycache__/wsgi.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/CRUD API using Function Based View/api/api/__pycache__/wsgi.cpython-38.pyc -------------------------------------------------------------------------------- /CRUD API using Function Based View/api/api/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for api project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /CRUD API using Function Based View/api/api/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for api project. 3 | 4 | Generated by 'django-admin startproject' using Django 3.2.6. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/3.2/ref/settings/ 11 | """ 12 | 13 | from pathlib import Path 14 | 15 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 16 | BASE_DIR = Path(__file__).resolve().parent.parent 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'django-insecure-1z^fk2^g!_4#rkewry#=j&_echz&n#!#w)_yg37d5$a0#@4sku' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'app', 41 | 'rest_framework' 42 | ] 43 | 44 | MIDDLEWARE = [ 45 | 'django.middleware.security.SecurityMiddleware', 46 | 'django.contrib.sessions.middleware.SessionMiddleware', 47 | 'django.middleware.common.CommonMiddleware', 48 | 'django.middleware.csrf.CsrfViewMiddleware', 49 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 50 | 'django.contrib.messages.middleware.MessageMiddleware', 51 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 52 | ] 53 | 54 | ROOT_URLCONF = 'api.urls' 55 | 56 | TEMPLATES = [ 57 | { 58 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 59 | 'DIRS': [], 60 | 'APP_DIRS': True, 61 | 'OPTIONS': { 62 | 'context_processors': [ 63 | 'django.template.context_processors.debug', 64 | 'django.template.context_processors.request', 65 | 'django.contrib.auth.context_processors.auth', 66 | 'django.contrib.messages.context_processors.messages', 67 | ], 68 | }, 69 | }, 70 | ] 71 | 72 | WSGI_APPLICATION = 'api.wsgi.application' 73 | 74 | 75 | # Database 76 | # https://docs.djangoproject.com/en/3.2/ref/settings/#databases 77 | 78 | DATABASES = { 79 | 'default': { 80 | 'ENGINE': 'django.db.backends.sqlite3', 81 | 'NAME': BASE_DIR / 'db.sqlite3', 82 | } 83 | } 84 | 85 | 86 | # Password validation 87 | # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators 88 | 89 | AUTH_PASSWORD_VALIDATORS = [ 90 | { 91 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 92 | }, 93 | { 94 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 95 | }, 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 98 | }, 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 101 | }, 102 | ] 103 | 104 | 105 | # Internationalization 106 | # https://docs.djangoproject.com/en/3.2/topics/i18n/ 107 | 108 | LANGUAGE_CODE = 'en-us' 109 | 110 | TIME_ZONE = 'UTC' 111 | 112 | USE_I18N = True 113 | 114 | USE_L10N = True 115 | 116 | USE_TZ = True 117 | 118 | 119 | # Static files (CSS, JavaScript, Images) 120 | # https://docs.djangoproject.com/en/3.2/howto/static-files/ 121 | 122 | STATIC_URL = '/static/' 123 | 124 | # Default primary key field type 125 | # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field 126 | 127 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 128 | -------------------------------------------------------------------------------- /CRUD API using Function Based View/api/api/urls.py: -------------------------------------------------------------------------------- 1 | """api URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/3.2/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path 18 | from django.urls.conf import include 19 | 20 | urlpatterns = [ 21 | path('admin/', admin.site.urls), 22 | path('',include('app.urls')) 23 | ] 24 | -------------------------------------------------------------------------------- /CRUD API using Function Based View/api/api/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for api project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /CRUD API using Function Based View/api/app/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/CRUD API using Function Based View/api/app/__init__.py -------------------------------------------------------------------------------- /CRUD API using Function Based View/api/app/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/CRUD API using Function Based View/api/app/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /CRUD API using Function Based View/api/app/__pycache__/admin.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/CRUD API using Function Based View/api/app/__pycache__/admin.cpython-38.pyc -------------------------------------------------------------------------------- /CRUD API using Function Based View/api/app/__pycache__/apps.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/CRUD API using Function Based View/api/app/__pycache__/apps.cpython-38.pyc -------------------------------------------------------------------------------- /CRUD API using Function Based View/api/app/__pycache__/models.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/CRUD API using Function Based View/api/app/__pycache__/models.cpython-38.pyc -------------------------------------------------------------------------------- /CRUD API using Function Based View/api/app/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from .models import Teacher 3 | # Register your models here. 4 | 5 | @admin.register(Teacher) 6 | class TeacherAdmin(admin.ModelAdmin): 7 | list_display = ['id','full_name','address','salary'] -------------------------------------------------------------------------------- /CRUD API using Function Based View/api/app/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class AppConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'app' 7 | -------------------------------------------------------------------------------- /CRUD API using Function Based View/api/app/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.2.6 on 2021-08-31 11:21 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | initial = True 9 | 10 | dependencies = [ 11 | ] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name='Teacher', 16 | fields=[ 17 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 18 | ('full_name', models.CharField(max_length=100)), 19 | ('address', models.CharField(max_length=100)), 20 | ('salary', models.BigIntegerField()), 21 | ], 22 | ), 23 | ] 24 | -------------------------------------------------------------------------------- /CRUD API using Function Based View/api/app/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/CRUD API using Function Based View/api/app/migrations/__init__.py -------------------------------------------------------------------------------- /CRUD API using Function Based View/api/app/migrations/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/CRUD API using Function Based View/api/app/migrations/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /CRUD API using Function Based View/api/app/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | class Teacher(models.Model): 5 | full_name = models.CharField(max_length=100) 6 | address = models.CharField(max_length=100) 7 | salary = models.BigIntegerField() -------------------------------------------------------------------------------- /CRUD API using Function Based View/api/app/serializer.py: -------------------------------------------------------------------------------- 1 | from app.models import Teacher 2 | from rest_framework import serializers 3 | 4 | class TeacherSerializer(serializers.Serializer): 5 | full_name = serializers.CharField(max_length=100) 6 | address = serializers.CharField(max_length=100) 7 | salary = serializers.IntegerField() 8 | def create(self,validated_data): 9 | return Teacher.objects.create(**validated_data) 10 | 11 | def update(self,instance,validated_data): 12 | instance.full_name = validated_data.get('full_name',instance.full_name) 13 | instance.address = validated_data.get('address',instance.address) 14 | instance.salary = validated_data.get('salary',instance.salary) 15 | instance.save() 16 | return instance 17 | 18 | -------------------------------------------------------------------------------- /CRUD API using Function Based View/api/app/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /CRUD API using Function Based View/api/app/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | from .views import apiFunction 3 | urlpatterns = [ 4 | path('api/',apiFunction,name='api') 5 | ] 6 | -------------------------------------------------------------------------------- /CRUD API using Function Based View/api/app/views.py: -------------------------------------------------------------------------------- 1 | from functools import partial 2 | import re 3 | from django.shortcuts import render 4 | from django.http import JsonResponse 5 | import io 6 | from rest_framework import serializers 7 | from rest_framework.fields import ReadOnlyField 8 | from.models import Teacher 9 | from rest_framework.parsers import JSONParser 10 | from .serializer import TeacherSerializer 11 | from django.views.decorators.csrf import csrf_exempt 12 | from .serializer import TeacherSerializer 13 | 14 | # Create your views here. 15 | 16 | 17 | @csrf_exempt 18 | def apiFunction(request): 19 | if request.method == 'GET': 20 | stream = io.BytesIO(request.body) 21 | python_data = JSONParser().parse(stream) 22 | id = python_data.get('id') 23 | if id is not None: 24 | get_data = Teacher.objects.get(id= id) 25 | serializer = TeacherSerializer(get_data) 26 | else: 27 | get_data = Teacher.objects.all() 28 | serializer = TeacherSerializer(get_data,many=True) 29 | return JsonResponse({'success':serializer.data}) 30 | 31 | if request.method == 'POST': 32 | stream = io.BytesIO(request.body) 33 | python_data = JSONParser().parse(stream) 34 | serializer = TeacherSerializer(data = python_data) 35 | if serializer.is_valid(): 36 | serializer.save() 37 | return JsonResponse({'message':'Data is post successfully'}) 38 | else: 39 | return JsonResponse(serializer.errors) 40 | 41 | if request.method == 'PUT': 42 | stream = io.BytesIO(request.body) 43 | python_data = JSONParser().parse(stream) 44 | id = python_data.get('id') 45 | obj = Teacher.objects.get(id = id) 46 | print(obj) 47 | print(obj.full_name) 48 | serializer = TeacherSerializer(obj,data=python_data,partial=True) 49 | if serializer.is_valid(): 50 | serializer.save() 51 | obj = Teacher.objects.get(id = id) 52 | return JsonResponse({'message':'Data is updated successfully!'}) 53 | else: 54 | return JsonResponse(serializer.errors) 55 | 56 | if request.method == 'DELETE': 57 | stream = io.BytesIO(request.body) 58 | python_data = JSONParser().parse(stream) 59 | obj = Teacher.objects.get(id = python_data.get('id')) 60 | if python_data.get('id') is not None: 61 | obj.delete() 62 | return JsonResponse({'Message':'Data is deleted successfully! '}) 63 | else: 64 | return JsonResponse({'Message':'Cannot delete!'}) 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /CRUD API using Function Based View/api/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/CRUD API using Function Based View/api/db.sqlite3 -------------------------------------------------------------------------------- /CRUD API using Function Based View/api/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /Class Based API View (CRUD)/api/api/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/Class Based API View (CRUD)/api/api/__init__.py -------------------------------------------------------------------------------- /Class Based API View (CRUD)/api/api/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for api project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /Class Based API View (CRUD)/api/api/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for api project. 3 | 4 | Generated by 'django-admin startproject' using Django 3.2.6. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/3.2/ref/settings/ 11 | """ 12 | 13 | from pathlib import Path 14 | 15 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 16 | BASE_DIR = Path(__file__).resolve().parent.parent 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'django-insecure-si^8pj(=&c^w_t(&j3zm+fu=9hsex^8ky6!3a5ivi7gm#k(nd)' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'app', 41 | 'rest_framework' 42 | ] 43 | 44 | MIDDLEWARE = [ 45 | 'django.middleware.security.SecurityMiddleware', 46 | 'django.contrib.sessions.middleware.SessionMiddleware', 47 | 'django.middleware.common.CommonMiddleware', 48 | 'django.middleware.csrf.CsrfViewMiddleware', 49 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 50 | 'django.contrib.messages.middleware.MessageMiddleware', 51 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 52 | ] 53 | 54 | ROOT_URLCONF = 'api.urls' 55 | 56 | TEMPLATES = [ 57 | { 58 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 59 | 'DIRS': [], 60 | 'APP_DIRS': True, 61 | 'OPTIONS': { 62 | 'context_processors': [ 63 | 'django.template.context_processors.debug', 64 | 'django.template.context_processors.request', 65 | 'django.contrib.auth.context_processors.auth', 66 | 'django.contrib.messages.context_processors.messages', 67 | ], 68 | }, 69 | }, 70 | ] 71 | 72 | WSGI_APPLICATION = 'api.wsgi.application' 73 | 74 | 75 | # Database 76 | # https://docs.djangoproject.com/en/3.2/ref/settings/#databases 77 | 78 | DATABASES = { 79 | 'default': { 80 | 'ENGINE': 'django.db.backends.sqlite3', 81 | 'NAME': BASE_DIR / 'db.sqlite3', 82 | } 83 | } 84 | 85 | 86 | # Password validation 87 | # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators 88 | 89 | AUTH_PASSWORD_VALIDATORS = [ 90 | { 91 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 92 | }, 93 | { 94 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 95 | }, 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 98 | }, 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 101 | }, 102 | ] 103 | 104 | 105 | # Internationalization 106 | # https://docs.djangoproject.com/en/3.2/topics/i18n/ 107 | 108 | LANGUAGE_CODE = 'en-us' 109 | 110 | TIME_ZONE = 'UTC' 111 | 112 | USE_I18N = True 113 | 114 | USE_L10N = True 115 | 116 | USE_TZ = True 117 | 118 | 119 | # Static files (CSS, JavaScript, Images) 120 | # https://docs.djangoproject.com/en/3.2/howto/static-files/ 121 | 122 | STATIC_URL = '/static/' 123 | 124 | # Default primary key field type 125 | # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field 126 | 127 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 128 | -------------------------------------------------------------------------------- /Class Based API View (CRUD)/api/api/urls.py: -------------------------------------------------------------------------------- 1 | """api URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/3.2/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path 18 | from app.views import TeacherAPI 19 | urlpatterns = [ 20 | path('admin/', admin.site.urls), 21 | path('api/',TeacherAPI.as_view()), 22 | path('api//',TeacherAPI.as_view()) 23 | 24 | ] 25 | -------------------------------------------------------------------------------- /Class Based API View (CRUD)/api/api/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for api project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /Class Based API View (CRUD)/api/app/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/Class Based API View (CRUD)/api/app/__init__.py -------------------------------------------------------------------------------- /Class Based API View (CRUD)/api/app/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from .models import Teacher 3 | # Register your models here. 4 | 5 | @admin.register(Teacher) 6 | class TeacherAdmin(admin.ModelAdmin): 7 | list_display = ['id','full_name','address','salary'] -------------------------------------------------------------------------------- /Class Based API View (CRUD)/api/app/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class AppConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'app' 7 | -------------------------------------------------------------------------------- /Class Based API View (CRUD)/api/app/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.2.6 on 2021-09-03 15:29 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | initial = True 9 | 10 | dependencies = [ 11 | ] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name='Teacher', 16 | fields=[ 17 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 18 | ('full_name', models.CharField(max_length=100)), 19 | ('address', models.CharField(max_length=100)), 20 | ('salary', models.BigIntegerField()), 21 | ], 22 | ), 23 | ] 24 | -------------------------------------------------------------------------------- /Class Based API View (CRUD)/api/app/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/Class Based API View (CRUD)/api/app/migrations/__init__.py -------------------------------------------------------------------------------- /Class Based API View (CRUD)/api/app/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | class Teacher(models.Model): 5 | full_name = models.CharField(max_length=100) 6 | address = models.CharField(max_length=100) 7 | salary = models.BigIntegerField() -------------------------------------------------------------------------------- /Class Based API View (CRUD)/api/app/serializer.py: -------------------------------------------------------------------------------- 1 | from django.db.models import fields 2 | from app.models import Teacher 3 | from rest_framework import serializers 4 | 5 | class TeacherSerializer(serializers.ModelSerializer): 6 | class Meta: 7 | model = Teacher 8 | fields = ['full_name','salary','address'] 9 | 10 | 11 | -------------------------------------------------------------------------------- /Class Based API View (CRUD)/api/app/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /Class Based API View (CRUD)/api/app/views.py: -------------------------------------------------------------------------------- 1 | from .serializer import TeacherSerializer 2 | from .models import Teacher 3 | from rest_framework.views import APIView 4 | from rest_framework.response import Response 5 | from rest_framework.decorators import api_view 6 | # Create your views here. 7 | 8 | 9 | class TeacherAPI(APIView): 10 | def get(self,request,id=None,format=None): 11 | if id is not None: 12 | obj = Teacher.objects.get(id=id) 13 | serializer = TeacherSerializer(obj) 14 | else: 15 | obj = Teacher.objects.all() 16 | serializer = TeacherSerializer(obj,many=True) 17 | return Response(serializer.data) 18 | 19 | def post(self,request,format=None): 20 | dt = request.data 21 | serializer = TeacherSerializer(data = dt) 22 | if serializer.is_valid(): 23 | serializer.save() 24 | return Response({'message':'Detail is posted!'}) 25 | else: 26 | return Response({'message':'Something went wrong'}) 27 | 28 | def put(self,request,format=None): 29 | data = request.data 30 | id = request.data.get('id') 31 | obj = Teacher.objects.get(id=id) 32 | serializer = TeacherSerializer(obj,data=data) 33 | if serializer.is_valid(): 34 | serializer.save() 35 | return Response({'message':'Data is updated completely!!'}) 36 | else: 37 | return Response(serializer.errors) 38 | 39 | def patch(self,request,format=None): 40 | data = request.data 41 | id = request.data.get('id') 42 | obj = Teacher.objects.get(id=id) 43 | serializer = TeacherSerializer(obj,data=data,partial=True) 44 | if serializer.is_valid(): 45 | serializer.save() 46 | return Response({'message':'Data is updated partially!!'}) 47 | else: 48 | return Response(serializer.errors) 49 | 50 | def delete(self,request,id=None,format=None): 51 | if id is not None: 52 | obj = Teacher.objects.get(id = id) 53 | obj.delete() 54 | return Response({"message":"Data is deleted successfully!"}) 55 | else: 56 | return Response({"message":"Data is deleted not deleted!"}) 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /Class Based API View (CRUD)/api/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/Class Based API View (CRUD)/api/db.sqlite3 -------------------------------------------------------------------------------- /Class Based API View (CRUD)/api/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /Concrete View Class Part-I/api/api/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/Concrete View Class Part-I/api/api/__init__.py -------------------------------------------------------------------------------- /Concrete View Class Part-I/api/api/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for api project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /Concrete View Class Part-I/api/api/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for api project. 3 | 4 | Generated by 'django-admin startproject' using Django 3.2.6. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/3.2/ref/settings/ 11 | """ 12 | 13 | from pathlib import Path 14 | 15 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 16 | BASE_DIR = Path(__file__).resolve().parent.parent 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'django-insecure-si^8pj(=&c^w_t(&j3zm+fu=9hsex^8ky6!3a5ivi7gm#k(nd)' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'app', 41 | 'rest_framework' 42 | ] 43 | 44 | MIDDLEWARE = [ 45 | 'django.middleware.security.SecurityMiddleware', 46 | 'django.contrib.sessions.middleware.SessionMiddleware', 47 | 'django.middleware.common.CommonMiddleware', 48 | 'django.middleware.csrf.CsrfViewMiddleware', 49 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 50 | 'django.contrib.messages.middleware.MessageMiddleware', 51 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 52 | ] 53 | 54 | ROOT_URLCONF = 'api.urls' 55 | 56 | TEMPLATES = [ 57 | { 58 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 59 | 'DIRS': [], 60 | 'APP_DIRS': True, 61 | 'OPTIONS': { 62 | 'context_processors': [ 63 | 'django.template.context_processors.debug', 64 | 'django.template.context_processors.request', 65 | 'django.contrib.auth.context_processors.auth', 66 | 'django.contrib.messages.context_processors.messages', 67 | ], 68 | }, 69 | }, 70 | ] 71 | 72 | WSGI_APPLICATION = 'api.wsgi.application' 73 | 74 | 75 | # Database 76 | # https://docs.djangoproject.com/en/3.2/ref/settings/#databases 77 | 78 | DATABASES = { 79 | 'default': { 80 | 'ENGINE': 'django.db.backends.sqlite3', 81 | 'NAME': BASE_DIR / 'db.sqlite3', 82 | } 83 | } 84 | 85 | 86 | # Password validation 87 | # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators 88 | 89 | AUTH_PASSWORD_VALIDATORS = [ 90 | { 91 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 92 | }, 93 | { 94 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 95 | }, 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 98 | }, 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 101 | }, 102 | ] 103 | 104 | 105 | # Internationalization 106 | # https://docs.djangoproject.com/en/3.2/topics/i18n/ 107 | 108 | LANGUAGE_CODE = 'en-us' 109 | 110 | TIME_ZONE = 'UTC' 111 | 112 | USE_I18N = True 113 | 114 | USE_L10N = True 115 | 116 | USE_TZ = True 117 | 118 | 119 | # Static files (CSS, JavaScript, Images) 120 | # https://docs.djangoproject.com/en/3.2/howto/static-files/ 121 | 122 | STATIC_URL = '/static/' 123 | 124 | # Default primary key field type 125 | # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field 126 | 127 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 128 | -------------------------------------------------------------------------------- /Concrete View Class Part-I/api/api/urls.py: -------------------------------------------------------------------------------- 1 | """api URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/3.2/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path 18 | from app.views import ListTeacherAPI,CreateTeacherAPI,RetriveTeacherAPI,DestroyTeacherAPI,UpdateTeacherAPI 19 | urlpatterns = [ 20 | path('admin/', admin.site.urls), 21 | path('api/list/',ListTeacherAPI.as_view()), 22 | path('api/create/',CreateTeacherAPI.as_view()), 23 | path('api/retrive//',RetriveTeacherAPI.as_view()), 24 | path('api/destroy//',DestroyTeacherAPI.as_view()), 25 | path('api/update//',UpdateTeacherAPI.as_view()), 26 | 27 | 28 | ] 29 | -------------------------------------------------------------------------------- /Concrete View Class Part-I/api/api/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for api project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /Concrete View Class Part-I/api/app/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/Concrete View Class Part-I/api/app/__init__.py -------------------------------------------------------------------------------- /Concrete View Class Part-I/api/app/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from .models import Teacher 3 | # Register your models here. 4 | 5 | @admin.register(Teacher) 6 | class TeacherAdmin(admin.ModelAdmin): 7 | list_display = ['id','full_name','address','salary'] -------------------------------------------------------------------------------- /Concrete View Class Part-I/api/app/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class AppConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'app' 7 | -------------------------------------------------------------------------------- /Concrete View Class Part-I/api/app/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.2.6 on 2021-09-03 15:29 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | initial = True 9 | 10 | dependencies = [ 11 | ] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name='Teacher', 16 | fields=[ 17 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 18 | ('full_name', models.CharField(max_length=100)), 19 | ('address', models.CharField(max_length=100)), 20 | ('salary', models.BigIntegerField()), 21 | ], 22 | ), 23 | ] 24 | -------------------------------------------------------------------------------- /Concrete View Class Part-I/api/app/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/Concrete View Class Part-I/api/app/migrations/__init__.py -------------------------------------------------------------------------------- /Concrete View Class Part-I/api/app/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | class Teacher(models.Model): 5 | full_name = models.CharField(max_length=100) 6 | address = models.CharField(max_length=100) 7 | salary = models.BigIntegerField() -------------------------------------------------------------------------------- /Concrete View Class Part-I/api/app/serializer.py: -------------------------------------------------------------------------------- 1 | from django.db.models import fields 2 | from app.models import Teacher 3 | from rest_framework import serializers 4 | 5 | class TeacherSerializer(serializers.ModelSerializer): 6 | class Meta: 7 | model = Teacher 8 | fields = ['id','full_name','salary','address'] 9 | 10 | 11 | -------------------------------------------------------------------------------- /Concrete View Class Part-I/api/app/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /Concrete View Class Part-I/api/app/views.py: -------------------------------------------------------------------------------- 1 | from .serializer import TeacherSerializer 2 | from .models import Teacher 3 | from rest_framework.generics import ListAPIView,CreateAPIView,RetrieveAPIView,UpdateAPIView,DestroyAPIView 4 | # Create your views here. 5 | 6 | 7 | class ListTeacherAPI(ListAPIView): 8 | queryset = Teacher.objects.all() 9 | serializer_class = TeacherSerializer 10 | 11 | 12 | class CreateTeacherAPI(CreateAPIView): 13 | queryset = Teacher.objects.all() 14 | serializer_class = TeacherSerializer 15 | 16 | class RetriveTeacherAPI(RetrieveAPIView): 17 | queryset = Teacher.objects.all() 18 | serializer_class = TeacherSerializer 19 | 20 | class UpdateTeacherAPI(UpdateAPIView): 21 | queryset = Teacher.objects.all() 22 | serializer_class = TeacherSerializer 23 | 24 | class DestroyTeacherAPI(DestroyAPIView): 25 | queryset = Teacher.objects.all() 26 | serializer_class = TeacherSerializer -------------------------------------------------------------------------------- /Concrete View Class Part-I/api/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/Concrete View Class Part-I/api/db.sqlite3 -------------------------------------------------------------------------------- /Concrete View Class Part-I/api/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /Concrete View Class Part-II/api/api/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/Concrete View Class Part-II/api/api/__init__.py -------------------------------------------------------------------------------- /Concrete View Class Part-II/api/api/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for api project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /Concrete View Class Part-II/api/api/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for api project. 3 | 4 | Generated by 'django-admin startproject' using Django 3.2.6. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/3.2/ref/settings/ 11 | """ 12 | 13 | from pathlib import Path 14 | 15 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 16 | BASE_DIR = Path(__file__).resolve().parent.parent 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'django-insecure-si^8pj(=&c^w_t(&j3zm+fu=9hsex^8ky6!3a5ivi7gm#k(nd)' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'app', 41 | 'rest_framework' 42 | ] 43 | 44 | MIDDLEWARE = [ 45 | 'django.middleware.security.SecurityMiddleware', 46 | 'django.contrib.sessions.middleware.SessionMiddleware', 47 | 'django.middleware.common.CommonMiddleware', 48 | 'django.middleware.csrf.CsrfViewMiddleware', 49 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 50 | 'django.contrib.messages.middleware.MessageMiddleware', 51 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 52 | ] 53 | 54 | ROOT_URLCONF = 'api.urls' 55 | 56 | TEMPLATES = [ 57 | { 58 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 59 | 'DIRS': [], 60 | 'APP_DIRS': True, 61 | 'OPTIONS': { 62 | 'context_processors': [ 63 | 'django.template.context_processors.debug', 64 | 'django.template.context_processors.request', 65 | 'django.contrib.auth.context_processors.auth', 66 | 'django.contrib.messages.context_processors.messages', 67 | ], 68 | }, 69 | }, 70 | ] 71 | 72 | WSGI_APPLICATION = 'api.wsgi.application' 73 | 74 | 75 | # Database 76 | # https://docs.djangoproject.com/en/3.2/ref/settings/#databases 77 | 78 | DATABASES = { 79 | 'default': { 80 | 'ENGINE': 'django.db.backends.sqlite3', 81 | 'NAME': BASE_DIR / 'db.sqlite3', 82 | } 83 | } 84 | 85 | 86 | # Password validation 87 | # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators 88 | 89 | AUTH_PASSWORD_VALIDATORS = [ 90 | { 91 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 92 | }, 93 | { 94 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 95 | }, 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 98 | }, 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 101 | }, 102 | ] 103 | 104 | 105 | # Internationalization 106 | # https://docs.djangoproject.com/en/3.2/topics/i18n/ 107 | 108 | LANGUAGE_CODE = 'en-us' 109 | 110 | TIME_ZONE = 'UTC' 111 | 112 | USE_I18N = True 113 | 114 | USE_L10N = True 115 | 116 | USE_TZ = True 117 | 118 | 119 | # Static files (CSS, JavaScript, Images) 120 | # https://docs.djangoproject.com/en/3.2/howto/static-files/ 121 | 122 | STATIC_URL = '/static/' 123 | 124 | # Default primary key field type 125 | # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field 126 | 127 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 128 | -------------------------------------------------------------------------------- /Concrete View Class Part-II/api/api/urls.py: -------------------------------------------------------------------------------- 1 | """api URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/3.2/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path 18 | from app.views import ListCreateTeacherAPI,RetrieveDestroyTeacherAPI,RetrieveUpdateDestroyTeacherAPI,RetrieveUpdateTeacherAPI 19 | urlpatterns = [ 20 | path('admin/', admin.site.urls), 21 | path('api/listCreate/',ListCreateTeacherAPI.as_view()), 22 | path('api/retriveDestroy//',RetrieveDestroyTeacherAPI.as_view()), 23 | path('api/retriveUpdateDestroy//',RetrieveUpdateDestroyTeacherAPI.as_view()), 24 | path('api/retriveUpdate//',RetrieveUpdateTeacherAPI.as_view()), 25 | 26 | ] 27 | -------------------------------------------------------------------------------- /Concrete View Class Part-II/api/api/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for api project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /Concrete View Class Part-II/api/app/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/Concrete View Class Part-II/api/app/__init__.py -------------------------------------------------------------------------------- /Concrete View Class Part-II/api/app/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from .models import Teacher 3 | # Register your models here. 4 | 5 | @admin.register(Teacher) 6 | class TeacherAdmin(admin.ModelAdmin): 7 | list_display = ['id','full_name','address','salary'] -------------------------------------------------------------------------------- /Concrete View Class Part-II/api/app/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class AppConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'app' 7 | -------------------------------------------------------------------------------- /Concrete View Class Part-II/api/app/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.2.6 on 2021-09-03 15:29 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | initial = True 9 | 10 | dependencies = [ 11 | ] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name='Teacher', 16 | fields=[ 17 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 18 | ('full_name', models.CharField(max_length=100)), 19 | ('address', models.CharField(max_length=100)), 20 | ('salary', models.BigIntegerField()), 21 | ], 22 | ), 23 | ] 24 | -------------------------------------------------------------------------------- /Concrete View Class Part-II/api/app/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/Concrete View Class Part-II/api/app/migrations/__init__.py -------------------------------------------------------------------------------- /Concrete View Class Part-II/api/app/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | class Teacher(models.Model): 5 | full_name = models.CharField(max_length=100) 6 | address = models.CharField(max_length=100) 7 | salary = models.BigIntegerField() -------------------------------------------------------------------------------- /Concrete View Class Part-II/api/app/serializer.py: -------------------------------------------------------------------------------- 1 | from django.db.models import fields 2 | from app.models import Teacher 3 | from rest_framework import serializers 4 | 5 | class TeacherSerializer(serializers.ModelSerializer): 6 | class Meta: 7 | model = Teacher 8 | fields = ['id','full_name','salary','address'] 9 | 10 | 11 | -------------------------------------------------------------------------------- /Concrete View Class Part-II/api/app/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /Concrete View Class Part-II/api/app/views.py: -------------------------------------------------------------------------------- 1 | from .serializer import TeacherSerializer 2 | from .models import Teacher 3 | from rest_framework.generics import ListCreateAPIView,RetrieveDestroyAPIView,RetrieveUpdateAPIView,RetrieveUpdateDestroyAPIView 4 | # Create your views here. 5 | 6 | 7 | class ListCreateTeacherAPI(ListCreateAPIView): 8 | queryset = Teacher.objects.all() 9 | serializer_class = TeacherSerializer 10 | 11 | 12 | class RetrieveDestroyTeacherAPI(RetrieveDestroyAPIView): 13 | queryset = Teacher.objects.all() 14 | serializer_class = TeacherSerializer 15 | 16 | class RetrieveUpdateTeacherAPI(RetrieveUpdateAPIView): 17 | queryset = Teacher.objects.all() 18 | serializer_class = TeacherSerializer 19 | 20 | class RetrieveUpdateDestroyTeacherAPI(RetrieveUpdateDestroyAPIView): 21 | queryset = Teacher.objects.all() 22 | serializer_class = TeacherSerializer 23 | -------------------------------------------------------------------------------- /Concrete View Class Part-II/api/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/Concrete View Class Part-II/api/db.sqlite3 -------------------------------------------------------------------------------- /Concrete View Class Part-II/api/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /Function Based API View (CRUD)/api/api/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/Function Based API View (CRUD)/api/api/__init__.py -------------------------------------------------------------------------------- /Function Based API View (CRUD)/api/api/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for api project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /Function Based API View (CRUD)/api/api/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for api project. 3 | 4 | Generated by 'django-admin startproject' using Django 3.2.6. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/3.2/ref/settings/ 11 | """ 12 | 13 | from pathlib import Path 14 | 15 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 16 | BASE_DIR = Path(__file__).resolve().parent.parent 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'django-insecure-si^8pj(=&c^w_t(&j3zm+fu=9hsex^8ky6!3a5ivi7gm#k(nd)' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'app', 41 | 'rest_framework' 42 | ] 43 | 44 | MIDDLEWARE = [ 45 | 'django.middleware.security.SecurityMiddleware', 46 | 'django.contrib.sessions.middleware.SessionMiddleware', 47 | 'django.middleware.common.CommonMiddleware', 48 | 'django.middleware.csrf.CsrfViewMiddleware', 49 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 50 | 'django.contrib.messages.middleware.MessageMiddleware', 51 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 52 | ] 53 | 54 | ROOT_URLCONF = 'api.urls' 55 | 56 | TEMPLATES = [ 57 | { 58 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 59 | 'DIRS': [], 60 | 'APP_DIRS': True, 61 | 'OPTIONS': { 62 | 'context_processors': [ 63 | 'django.template.context_processors.debug', 64 | 'django.template.context_processors.request', 65 | 'django.contrib.auth.context_processors.auth', 66 | 'django.contrib.messages.context_processors.messages', 67 | ], 68 | }, 69 | }, 70 | ] 71 | 72 | WSGI_APPLICATION = 'api.wsgi.application' 73 | 74 | 75 | # Database 76 | # https://docs.djangoproject.com/en/3.2/ref/settings/#databases 77 | 78 | DATABASES = { 79 | 'default': { 80 | 'ENGINE': 'django.db.backends.sqlite3', 81 | 'NAME': BASE_DIR / 'db.sqlite3', 82 | } 83 | } 84 | 85 | 86 | # Password validation 87 | # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators 88 | 89 | AUTH_PASSWORD_VALIDATORS = [ 90 | { 91 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 92 | }, 93 | { 94 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 95 | }, 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 98 | }, 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 101 | }, 102 | ] 103 | 104 | 105 | # Internationalization 106 | # https://docs.djangoproject.com/en/3.2/topics/i18n/ 107 | 108 | LANGUAGE_CODE = 'en-us' 109 | 110 | TIME_ZONE = 'UTC' 111 | 112 | USE_I18N = True 113 | 114 | USE_L10N = True 115 | 116 | USE_TZ = True 117 | 118 | 119 | # Static files (CSS, JavaScript, Images) 120 | # https://docs.djangoproject.com/en/3.2/howto/static-files/ 121 | 122 | STATIC_URL = '/static/' 123 | 124 | # Default primary key field type 125 | # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field 126 | 127 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 128 | -------------------------------------------------------------------------------- /Function Based API View (CRUD)/api/api/urls.py: -------------------------------------------------------------------------------- 1 | """api URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/3.2/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path 18 | from app.views import teacherAPI 19 | urlpatterns = [ 20 | path('admin/', admin.site.urls), 21 | path('api/',teacherAPI), 22 | path('api//',teacherAPI) 23 | 24 | ] 25 | -------------------------------------------------------------------------------- /Function Based API View (CRUD)/api/api/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for api project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /Function Based API View (CRUD)/api/app/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/Function Based API View (CRUD)/api/app/__init__.py -------------------------------------------------------------------------------- /Function Based API View (CRUD)/api/app/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from .models import Teacher 3 | # Register your models here. 4 | 5 | @admin.register(Teacher) 6 | class TeacherAdmin(admin.ModelAdmin): 7 | list_display = ['id','full_name','address','salary'] -------------------------------------------------------------------------------- /Function Based API View (CRUD)/api/app/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class AppConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'app' 7 | -------------------------------------------------------------------------------- /Function Based API View (CRUD)/api/app/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.2.6 on 2021-09-02 18:26 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | initial = True 9 | 10 | dependencies = [ 11 | ] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name='Teacher', 16 | fields=[ 17 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 18 | ('full_name', models.CharField(max_length=100)), 19 | ('address', models.CharField(max_length=100)), 20 | ('salary', models.BigIntegerField()), 21 | ], 22 | ), 23 | ] 24 | -------------------------------------------------------------------------------- /Function Based API View (CRUD)/api/app/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/Function Based API View (CRUD)/api/app/migrations/__init__.py -------------------------------------------------------------------------------- /Function Based API View (CRUD)/api/app/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | class Teacher(models.Model): 5 | full_name = models.CharField(max_length=100) 6 | address = models.CharField(max_length=100) 7 | salary = models.BigIntegerField() -------------------------------------------------------------------------------- /Function Based API View (CRUD)/api/app/serializer.py: -------------------------------------------------------------------------------- 1 | from django.db.models import fields 2 | from app.models import Teacher 3 | from rest_framework import serializers 4 | 5 | class TeacherSerializer(serializers.ModelSerializer): 6 | class Meta: 7 | model = Teacher 8 | fields = ['full_name','salary','address'] 9 | 10 | 11 | -------------------------------------------------------------------------------- /Function Based API View (CRUD)/api/app/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /Function Based API View (CRUD)/api/app/views.py: -------------------------------------------------------------------------------- 1 | from .serializer import TeacherSerializer 2 | from .models import Teacher 3 | from rest_framework.parsers import JSONParser 4 | from rest_framework.response import Response 5 | from rest_framework.decorators import api_view 6 | # Create your views here. 7 | 8 | @api_view(['GET','POST','PUT','PATCH','DELETE']) 9 | def teacherAPI(request,id=None): 10 | if request.method == 'GET': 11 | if id is not None: 12 | obj = Teacher.objects.get(id=id) 13 | serializer = TeacherSerializer(obj) 14 | else: 15 | obj = Teacher.objects.all() 16 | serializer = TeacherSerializer(obj,many=True) 17 | return Response(serializer.data) 18 | 19 | if request.method == 'POST': 20 | dt = request.data 21 | serializer = TeacherSerializer(data = dt) 22 | if serializer.is_valid(): 23 | serializer.save() 24 | return Response({'message':'Detail is posted!'}) 25 | else: 26 | return Response({'message':'Something went wrong'}) 27 | 28 | if request.method == 'PUT': 29 | data = request.data 30 | id = request.data.get('id') 31 | obj = Teacher.objects.get(id=id) 32 | serializer = TeacherSerializer(obj,data=data) 33 | if serializer.is_valid(): 34 | serializer.save() 35 | return Response({'message':'Data is updated completely!!'}) 36 | else: 37 | return Response(serializer.errors) 38 | 39 | if request.method == 'PATCH': 40 | data = request.data 41 | id = request.data.get('id') 42 | obj = Teacher.objects.get(id=id) 43 | serializer = TeacherSerializer(obj,data=data,partial=True) 44 | if serializer.is_valid(): 45 | serializer.save() 46 | return Response({'message':'Data is updated partially!!'}) 47 | else: 48 | return Response(serializer.errors) 49 | 50 | if request.method == 'DELETE': 51 | if id is not None: 52 | obj = Teacher.objects.get(id = id) 53 | obj.delete() 54 | return Response({"message":"Data is deleted successfully!"}) 55 | else: 56 | return Response({"message":"Data is deleted not deleted!"}) 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /Function Based API View (CRUD)/api/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/Function Based API View (CRUD)/api/db.sqlite3 -------------------------------------------------------------------------------- /Function Based API View (CRUD)/api/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /Generic API View and Mixins (CRUD)/api/api/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/Generic API View and Mixins (CRUD)/api/api/__init__.py -------------------------------------------------------------------------------- /Generic API View and Mixins (CRUD)/api/api/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for api project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /Generic API View and Mixins (CRUD)/api/api/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for api project. 3 | 4 | Generated by 'django-admin startproject' using Django 3.2.6. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/3.2/ref/settings/ 11 | """ 12 | 13 | from pathlib import Path 14 | 15 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 16 | BASE_DIR = Path(__file__).resolve().parent.parent 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'django-insecure-si^8pj(=&c^w_t(&j3zm+fu=9hsex^8ky6!3a5ivi7gm#k(nd)' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'app', 41 | 'rest_framework' 42 | ] 43 | 44 | MIDDLEWARE = [ 45 | 'django.middleware.security.SecurityMiddleware', 46 | 'django.contrib.sessions.middleware.SessionMiddleware', 47 | 'django.middleware.common.CommonMiddleware', 48 | 'django.middleware.csrf.CsrfViewMiddleware', 49 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 50 | 'django.contrib.messages.middleware.MessageMiddleware', 51 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 52 | ] 53 | 54 | ROOT_URLCONF = 'api.urls' 55 | 56 | TEMPLATES = [ 57 | { 58 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 59 | 'DIRS': [], 60 | 'APP_DIRS': True, 61 | 'OPTIONS': { 62 | 'context_processors': [ 63 | 'django.template.context_processors.debug', 64 | 'django.template.context_processors.request', 65 | 'django.contrib.auth.context_processors.auth', 66 | 'django.contrib.messages.context_processors.messages', 67 | ], 68 | }, 69 | }, 70 | ] 71 | 72 | WSGI_APPLICATION = 'api.wsgi.application' 73 | 74 | 75 | # Database 76 | # https://docs.djangoproject.com/en/3.2/ref/settings/#databases 77 | 78 | DATABASES = { 79 | 'default': { 80 | 'ENGINE': 'django.db.backends.sqlite3', 81 | 'NAME': BASE_DIR / 'db.sqlite3', 82 | } 83 | } 84 | 85 | 86 | # Password validation 87 | # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators 88 | 89 | AUTH_PASSWORD_VALIDATORS = [ 90 | { 91 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 92 | }, 93 | { 94 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 95 | }, 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 98 | }, 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 101 | }, 102 | ] 103 | 104 | 105 | # Internationalization 106 | # https://docs.djangoproject.com/en/3.2/topics/i18n/ 107 | 108 | LANGUAGE_CODE = 'en-us' 109 | 110 | TIME_ZONE = 'UTC' 111 | 112 | USE_I18N = True 113 | 114 | USE_L10N = True 115 | 116 | USE_TZ = True 117 | 118 | 119 | # Static files (CSS, JavaScript, Images) 120 | # https://docs.djangoproject.com/en/3.2/howto/static-files/ 121 | 122 | STATIC_URL = '/static/' 123 | 124 | # Default primary key field type 125 | # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field 126 | 127 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 128 | -------------------------------------------------------------------------------- /Generic API View and Mixins (CRUD)/api/api/urls.py: -------------------------------------------------------------------------------- 1 | """api URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/3.2/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path 18 | from app.views import ListTeacherAPIPRD,ListTeacherAPIGP 19 | urlpatterns = [ 20 | path('admin/', admin.site.urls), 21 | path('api/',ListTeacherAPIGP.as_view()), 22 | path('api//',ListTeacherAPIPRD.as_view()) 23 | 24 | ] 25 | -------------------------------------------------------------------------------- /Generic API View and Mixins (CRUD)/api/api/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for api project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /Generic API View and Mixins (CRUD)/api/app/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/Generic API View and Mixins (CRUD)/api/app/__init__.py -------------------------------------------------------------------------------- /Generic API View and Mixins (CRUD)/api/app/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from .models import Teacher 3 | # Register your models here. 4 | 5 | @admin.register(Teacher) 6 | class TeacherAdmin(admin.ModelAdmin): 7 | list_display = ['id','full_name','address','salary'] -------------------------------------------------------------------------------- /Generic API View and Mixins (CRUD)/api/app/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class AppConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'app' 7 | -------------------------------------------------------------------------------- /Generic API View and Mixins (CRUD)/api/app/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.2.6 on 2021-09-03 15:29 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | initial = True 9 | 10 | dependencies = [ 11 | ] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name='Teacher', 16 | fields=[ 17 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 18 | ('full_name', models.CharField(max_length=100)), 19 | ('address', models.CharField(max_length=100)), 20 | ('salary', models.BigIntegerField()), 21 | ], 22 | ), 23 | ] 24 | -------------------------------------------------------------------------------- /Generic API View and Mixins (CRUD)/api/app/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/Generic API View and Mixins (CRUD)/api/app/migrations/__init__.py -------------------------------------------------------------------------------- /Generic API View and Mixins (CRUD)/api/app/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | class Teacher(models.Model): 5 | full_name = models.CharField(max_length=100) 6 | address = models.CharField(max_length=100) 7 | salary = models.BigIntegerField() -------------------------------------------------------------------------------- /Generic API View and Mixins (CRUD)/api/app/serializer.py: -------------------------------------------------------------------------------- 1 | from django.db.models import fields 2 | from app.models import Teacher 3 | from rest_framework import serializers 4 | 5 | class TeacherSerializer(serializers.ModelSerializer): 6 | class Meta: 7 | model = Teacher 8 | fields = ['full_name','salary','address'] 9 | 10 | 11 | -------------------------------------------------------------------------------- /Generic API View and Mixins (CRUD)/api/app/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /Generic API View and Mixins (CRUD)/api/app/views.py: -------------------------------------------------------------------------------- 1 | from .serializer import TeacherSerializer 2 | from .models import Teacher 3 | from rest_framework.views import APIView 4 | from rest_framework.response import Response 5 | from rest_framework.generics import GenericAPIView 6 | from rest_framework.mixins import ListModelMixin,CreateModelMixin,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin 7 | # Create your views here. 8 | 9 | class ListTeacherAPIGP(ListModelMixin,CreateModelMixin,GenericAPIView): 10 | queryset = Teacher.objects.all() 11 | serializer_class = TeacherSerializer 12 | def get(self,request,*arg,**kwargs): 13 | return self.list(request,*arg,**kwargs) 14 | 15 | def post(self,request,*arg,**kwargs): 16 | return self.create(request,*arg,**kwargs) 17 | 18 | 19 | 20 | class ListTeacherAPIPRD(UpdateModelMixin,DestroyModelMixin,RetrieveModelMixin,GenericAPIView): 21 | queryset = Teacher.objects.all() 22 | serializer_class = TeacherSerializer 23 | def get(self,request,*args,**kwargs): 24 | return self.retrieve(request,*args,**kwargs) 25 | 26 | def put(self,request,*args,**kwargs): 27 | return self.update(request,*args,**kwargs) 28 | 29 | def delete(self,request,*args,**kwargs): 30 | return self.destroy(request,*args,**kwargs) 31 | 32 | -------------------------------------------------------------------------------- /Generic API View and Mixins (CRUD)/api/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/Generic API View and Mixins (CRUD)/api/db.sqlite3 -------------------------------------------------------------------------------- /Generic API View and Mixins (CRUD)/api/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /Model Serializer in Django (CRUD)/api/api/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/Model Serializer in Django (CRUD)/api/api/__init__.py -------------------------------------------------------------------------------- /Model Serializer in Django (CRUD)/api/api/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for api project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /Model Serializer in Django (CRUD)/api/api/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for api project. 3 | 4 | Generated by 'django-admin startproject' using Django 3.2.6. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/3.2/ref/settings/ 11 | """ 12 | 13 | from pathlib import Path 14 | 15 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 16 | BASE_DIR = Path(__file__).resolve().parent.parent 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'django-insecure-si^8pj(=&c^w_t(&j3zm+fu=9hsex^8ky6!3a5ivi7gm#k(nd)' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'app', 41 | 'rest_framework' 42 | ] 43 | 44 | MIDDLEWARE = [ 45 | 'django.middleware.security.SecurityMiddleware', 46 | 'django.contrib.sessions.middleware.SessionMiddleware', 47 | 'django.middleware.common.CommonMiddleware', 48 | 'django.middleware.csrf.CsrfViewMiddleware', 49 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 50 | 'django.contrib.messages.middleware.MessageMiddleware', 51 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 52 | ] 53 | 54 | ROOT_URLCONF = 'api.urls' 55 | 56 | TEMPLATES = [ 57 | { 58 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 59 | 'DIRS': [], 60 | 'APP_DIRS': True, 61 | 'OPTIONS': { 62 | 'context_processors': [ 63 | 'django.template.context_processors.debug', 64 | 'django.template.context_processors.request', 65 | 'django.contrib.auth.context_processors.auth', 66 | 'django.contrib.messages.context_processors.messages', 67 | ], 68 | }, 69 | }, 70 | ] 71 | 72 | WSGI_APPLICATION = 'api.wsgi.application' 73 | 74 | 75 | # Database 76 | # https://docs.djangoproject.com/en/3.2/ref/settings/#databases 77 | 78 | DATABASES = { 79 | 'default': { 80 | 'ENGINE': 'django.db.backends.sqlite3', 81 | 'NAME': BASE_DIR / 'db.sqlite3', 82 | } 83 | } 84 | 85 | 86 | # Password validation 87 | # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators 88 | 89 | AUTH_PASSWORD_VALIDATORS = [ 90 | { 91 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 92 | }, 93 | { 94 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 95 | }, 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 98 | }, 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 101 | }, 102 | ] 103 | 104 | 105 | # Internationalization 106 | # https://docs.djangoproject.com/en/3.2/topics/i18n/ 107 | 108 | LANGUAGE_CODE = 'en-us' 109 | 110 | TIME_ZONE = 'UTC' 111 | 112 | USE_I18N = True 113 | 114 | USE_L10N = True 115 | 116 | USE_TZ = True 117 | 118 | 119 | # Static files (CSS, JavaScript, Images) 120 | # https://docs.djangoproject.com/en/3.2/howto/static-files/ 121 | 122 | STATIC_URL = '/static/' 123 | 124 | # Default primary key field type 125 | # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field 126 | 127 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 128 | -------------------------------------------------------------------------------- /Model Serializer in Django (CRUD)/api/api/urls.py: -------------------------------------------------------------------------------- 1 | """api URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/3.2/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path 18 | from app.views import TeacherAPI 19 | urlpatterns = [ 20 | path('admin/', admin.site.urls), 21 | path('api/',TeacherAPI.as_view()) 22 | ] 23 | -------------------------------------------------------------------------------- /Model Serializer in Django (CRUD)/api/api/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for api project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /Model Serializer in Django (CRUD)/api/app/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/Model Serializer in Django (CRUD)/api/app/__init__.py -------------------------------------------------------------------------------- /Model Serializer in Django (CRUD)/api/app/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from .models import Teacher 3 | # Register your models here. 4 | 5 | @admin.register(Teacher) 6 | class TeacherAdmin(admin.ModelAdmin): 7 | list_display = ['id','full_name','address','salary'] -------------------------------------------------------------------------------- /Model Serializer in Django (CRUD)/api/app/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class AppConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'app' 7 | -------------------------------------------------------------------------------- /Model Serializer in Django (CRUD)/api/app/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.2.6 on 2021-09-02 18:26 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | initial = True 9 | 10 | dependencies = [ 11 | ] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name='Teacher', 16 | fields=[ 17 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 18 | ('full_name', models.CharField(max_length=100)), 19 | ('address', models.CharField(max_length=100)), 20 | ('salary', models.BigIntegerField()), 21 | ], 22 | ), 23 | ] 24 | -------------------------------------------------------------------------------- /Model Serializer in Django (CRUD)/api/app/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/Model Serializer in Django (CRUD)/api/app/migrations/__init__.py -------------------------------------------------------------------------------- /Model Serializer in Django (CRUD)/api/app/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | class Teacher(models.Model): 5 | full_name = models.CharField(max_length=100) 6 | address = models.CharField(max_length=100) 7 | salary = models.BigIntegerField() -------------------------------------------------------------------------------- /Model Serializer in Django (CRUD)/api/app/serializer.py: -------------------------------------------------------------------------------- 1 | from django.db.models import fields 2 | from app.models import Teacher 3 | from rest_framework import serializers 4 | 5 | class TeacherSerializer(serializers.ModelSerializer): 6 | class Meta: 7 | model = Teacher 8 | fields = ['full_name','salary','address'] 9 | 10 | 11 | -------------------------------------------------------------------------------- /Model Serializer in Django (CRUD)/api/app/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /Model Serializer in Django (CRUD)/api/app/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | from django.views import View 3 | from django.views.decorators.csrf import csrf_exempt 4 | from django.utils.decorators import method_decorator 5 | from django.http import JsonResponse 6 | import re 7 | from .serializer import TeacherSerializer 8 | from .models import Teacher 9 | import io 10 | from rest_framework.parsers import JSONParser 11 | # Create your views here. 12 | 13 | @method_decorator(csrf_exempt,name='dispatch') 14 | class TeacherAPI(View): 15 | def get(self,request,*ar,**arg): 16 | stream = io.BytesIO(request.body) 17 | python_data = JSONParser().parse(stream) 18 | id = python_data.get('id') 19 | if id is not None: 20 | get_data = Teacher.objects.get(id= id) 21 | serializer = TeacherSerializer(get_data) 22 | else: 23 | get_data = Teacher.objects.all() 24 | serializer = TeacherSerializer(get_data,many=True) 25 | return JsonResponse({'success':serializer.data}) 26 | 27 | def post(self,request,*arg,**args): 28 | stream = io.BytesIO(request.body) 29 | python_data = JSONParser().parse(stream) 30 | serializer = TeacherSerializer(data = python_data) 31 | if serializer.is_valid(): 32 | serializer.save() 33 | return JsonResponse({'message':'Data is post successfully'}) 34 | else: 35 | return JsonResponse(serializer.errors) 36 | 37 | def put(self,request,*arg,**args): 38 | stream = io.BytesIO(request.body) 39 | python_data = JSONParser().parse(stream) 40 | id = python_data.get('id') 41 | obj = Teacher.objects.get(id = id) 42 | print(obj) 43 | print(obj.full_name) 44 | serializer = TeacherSerializer(obj,data=python_data,partial=True) 45 | if serializer.is_valid(): 46 | serializer.save() 47 | obj = Teacher.objects.get(id = id) 48 | return JsonResponse({'message':'Data is updated successfully!'}) 49 | else: 50 | return JsonResponse(serializer.errors) 51 | 52 | def delete(self,request,*arg,**args): 53 | stream = io.BytesIO(request.body) 54 | python_data = JSONParser().parse(stream) 55 | obj = Teacher.objects.get(id = python_data.get('id')) 56 | if python_data.get('id') is not None: 57 | obj.delete() 58 | return JsonResponse({'Message':'Data is deleted successfully! '}) 59 | else: 60 | return JsonResponse({'Message':'Cannot delete!'}) -------------------------------------------------------------------------------- /Model Serializer in Django (CRUD)/api/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srksuman/Django_Rest_Framework/06eb9f1f25371838d3a2ea9b5f39df35ab109263/Model Serializer in Django (CRUD)/api/db.sqlite3 -------------------------------------------------------------------------------- /Model Serializer in Django (CRUD)/api/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Django Rest Framework 2 | 3 | -------------------------------------------------------------------------------- /third_part_app.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | def get_function(id = None): 4 | dt = json.dumps({'id':id}) 5 | res = requests.get(url='http://127.0.0.1:8000/api/',data=dt) 6 | print(res.json()) 7 | 8 | # get_function() 9 | 10 | def post_function(id = None): 11 | dt = json.dumps({'full_name':'Hari Khanal','address':'Jorpati','salary':36520}) 12 | res = requests.post(url='http://127.0.0.1:8000/api/',data=dt) 13 | print(res.json()) 14 | 15 | # post_function() 16 | 17 | def put_function(): 18 | dt = json.dumps({'id':3,'full_name':'Sujan Raj','salary':2000,'address':'Thali'}) 19 | res = requests.put(url='http://127.0.0.1:8000/api/',data=dt) 20 | print(res.json()) 21 | 22 | # put_function() 23 | 24 | def delete_function(): 25 | dt = json.dumps({'id':3}) 26 | res = requests.delete(url='http://127.0.0.1:8000/api/',data=dt) 27 | print(res.json()) 28 | 29 | delete_function() --------------------------------------------------------------------------------