├── .gitignore ├── DjangoRestApiMongoDB ├── .project ├── DjangoRestApiMongoDB │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py └── tutorials │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ ├── 0001_initial.py │ └── __init__.py │ ├── models.py │ ├── serializers.py │ ├── tests.py │ ├── urls.py │ └── views.py └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | *.pyc 3 | .DS_Store 4 | /.coverage 5 | /dist/ 6 | /build/ 7 | /MANIFEST 8 | /wagtail.egg-info/ 9 | /docs/_build/ 10 | /.tox/ 11 | /venv 12 | /node_modules/ 13 | npm-debug.log* 14 | *.idea/ 15 | /*.egg/ 16 | /.cache/ 17 | /.pytest_cache/ 18 | 19 | ### JetBrains 20 | .idea/ 21 | *.iml 22 | *.ipr 23 | *.iws 24 | coverage/ 25 | client/node_modules 26 | 27 | ### vscode 28 | .vscode -------------------------------------------------------------------------------- /DjangoRestApiMongoDB/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | DjangoRestApiMongodb 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /DjangoRestApiMongoDB/DjangoRestApiMongoDB/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/django-rest-api-mongodb/16203423467dbefc860f1830046c2b45d2311825/DjangoRestApiMongoDB/DjangoRestApiMongoDB/__init__.py -------------------------------------------------------------------------------- /DjangoRestApiMongoDB/DjangoRestApiMongoDB/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for DjangoRestApiMongoDB project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.1.15. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.1/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/2.1/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'hux_-pn)wak^o_-n#g=-b$_m9zi+cak68gz+ba!0e)ijbijp8w' 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 | # Tutorials application 41 | 'tutorials.apps.TutorialsConfig', 42 | # CORS 43 | 'corsheaders', 44 | ] 45 | 46 | MIDDLEWARE = [ 47 | 'django.middleware.security.SecurityMiddleware', 48 | 'django.contrib.sessions.middleware.SessionMiddleware', 49 | 'django.middleware.csrf.CsrfViewMiddleware', 50 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 51 | 'django.contrib.messages.middleware.MessageMiddleware', 52 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 53 | # CORS 54 | 'corsheaders.middleware.CorsMiddleware', 55 | 'django.middleware.common.CommonMiddleware', 56 | ] 57 | 58 | CORS_ORIGIN_ALLOW_ALL = False 59 | CORS_ORIGIN_WHITELIST = ( 60 | 'http://localhost:8081', 61 | ) 62 | 63 | ROOT_URLCONF = 'DjangoRestApiMongoDB.urls' 64 | 65 | TEMPLATES = [ 66 | { 67 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 68 | 'DIRS': [], 69 | 'APP_DIRS': True, 70 | 'OPTIONS': { 71 | 'context_processors': [ 72 | 'django.template.context_processors.debug', 73 | 'django.template.context_processors.request', 74 | 'django.contrib.auth.context_processors.auth', 75 | 'django.contrib.messages.context_processors.messages', 76 | ], 77 | }, 78 | }, 79 | ] 80 | 81 | WSGI_APPLICATION = 'DjangoRestApiMongoDB.wsgi.application' 82 | 83 | 84 | # Database 85 | # https://docs.djangoproject.com/en/2.1/ref/settings/#databases 86 | 87 | DATABASES = { 88 | 'default': { 89 | 'ENGINE': 'djongo', 90 | 'NAME': 'bezkoder_db', 91 | 'HOST': '127.0.0.1', 92 | 'PORT': 27017, 93 | } 94 | } 95 | 96 | 97 | # Password validation 98 | # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators 99 | 100 | AUTH_PASSWORD_VALIDATORS = [ 101 | { 102 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 103 | }, 104 | { 105 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 106 | }, 107 | { 108 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 109 | }, 110 | { 111 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 112 | }, 113 | ] 114 | 115 | 116 | # Internationalization 117 | # https://docs.djangoproject.com/en/2.1/topics/i18n/ 118 | 119 | LANGUAGE_CODE = 'en-us' 120 | 121 | TIME_ZONE = 'UTC' 122 | 123 | USE_I18N = True 124 | 125 | USE_L10N = True 126 | 127 | USE_TZ = True 128 | 129 | 130 | # Static files (CSS, JavaScript, Images) 131 | # https://docs.djangoproject.com/en/2.1/howto/static-files/ 132 | 133 | STATIC_URL = '/static/' 134 | -------------------------------------------------------------------------------- /DjangoRestApiMongoDB/DjangoRestApiMongoDB/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url, include 2 | 3 | urlpatterns = [ 4 | url(r'^', include('tutorials.urls')), 5 | ] -------------------------------------------------------------------------------- /DjangoRestApiMongoDB/DjangoRestApiMongoDB/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for DjangoRestApiMongoDB 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/2.1/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', 'DjangoRestApiMongoDB.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /DjangoRestApiMongoDB/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == '__main__': 6 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoRestApiMongoDB.settings') 7 | try: 8 | from django.core.management import execute_from_command_line 9 | except ImportError as exc: 10 | raise ImportError( 11 | "Couldn't import Django. Are you sure it's installed and " 12 | "available on your PYTHONPATH environment variable? Did you " 13 | "forget to activate a virtual environment?" 14 | ) from exc 15 | execute_from_command_line(sys.argv) 16 | -------------------------------------------------------------------------------- /DjangoRestApiMongoDB/tutorials/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/django-rest-api-mongodb/16203423467dbefc860f1830046c2b45d2311825/DjangoRestApiMongoDB/tutorials/__init__.py -------------------------------------------------------------------------------- /DjangoRestApiMongoDB/tutorials/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /DjangoRestApiMongoDB/tutorials/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class TutorialsConfig(AppConfig): 5 | name = 'tutorials' 6 | -------------------------------------------------------------------------------- /DjangoRestApiMongoDB/tutorials/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.1.15 on 2020-03-30 02:14 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='Tutorial', 16 | fields=[ 17 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 18 | ('title', models.CharField(default='', max_length=70)), 19 | ('description', models.CharField(default='', max_length=200)), 20 | ('published', models.BooleanField(default=False)), 21 | ], 22 | ), 23 | ] 24 | -------------------------------------------------------------------------------- /DjangoRestApiMongoDB/tutorials/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/django-rest-api-mongodb/16203423467dbefc860f1830046c2b45d2311825/DjangoRestApiMongoDB/tutorials/migrations/__init__.py -------------------------------------------------------------------------------- /DjangoRestApiMongoDB/tutorials/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | 4 | class Tutorial(models.Model): 5 | title = models.CharField(max_length=70, blank=False, default='') 6 | description = models.CharField(max_length=200, blank=False, default='') 7 | published = models.BooleanField(default=False) 8 | -------------------------------------------------------------------------------- /DjangoRestApiMongoDB/tutorials/serializers.py: -------------------------------------------------------------------------------- 1 | from rest_framework import serializers 2 | from tutorials.models import Tutorial 3 | 4 | 5 | class TutorialSerializer(serializers.ModelSerializer): 6 | 7 | class Meta: 8 | model = Tutorial 9 | fields = ('id', 10 | 'title', 11 | 'description', 12 | 'published') 13 | -------------------------------------------------------------------------------- /DjangoRestApiMongoDB/tutorials/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /DjangoRestApiMongoDB/tutorials/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | from tutorials import views 3 | 4 | urlpatterns = [ 5 | url(r'^api/tutorials$', views.tutorial_list), 6 | url(r'^api/tutorials/(?P[0-9]+)$', views.tutorial_detail), 7 | url(r'^api/tutorials/published$', views.tutorial_list_published) 8 | ] 9 | -------------------------------------------------------------------------------- /DjangoRestApiMongoDB/tutorials/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | 3 | from django.http.response import JsonResponse 4 | from rest_framework.parsers import JSONParser 5 | from rest_framework import status 6 | 7 | from tutorials.models import Tutorial 8 | from tutorials.serializers import TutorialSerializer 9 | from rest_framework.decorators import api_view 10 | 11 | 12 | @api_view(['GET', 'POST', 'DELETE']) 13 | def tutorial_list(request): 14 | if request.method == 'GET': 15 | tutorials = Tutorial.objects.all() 16 | 17 | title = request.GET.get('title', None) 18 | if title is not None: 19 | tutorials = tutorials.filter(title__icontains=title) 20 | 21 | tutorials_serializer = TutorialSerializer(tutorials, many=True) 22 | return JsonResponse(tutorials_serializer.data, safe=False) 23 | # 'safe=False' for objects serialization 24 | 25 | elif request.method == 'POST': 26 | tutorial_data = JSONParser().parse(request) 27 | tutorial_serializer = TutorialSerializer(data=tutorial_data) 28 | if tutorial_serializer.is_valid(): 29 | tutorial_serializer.save() 30 | return JsonResponse(tutorial_serializer.data, status=status.HTTP_201_CREATED) 31 | return JsonResponse(tutorial_serializer.errors, status=status.HTTP_400_BAD_REQUEST) 32 | 33 | elif request.method == 'DELETE': 34 | count = Tutorial.objects.all().delete() 35 | return JsonResponse({'message': '{} Tutorials were deleted successfully!'.format(count[0])}, status=status.HTTP_204_NO_CONTENT) 36 | 37 | 38 | @api_view(['GET', 'PUT', 'DELETE']) 39 | def tutorial_detail(request, pk): 40 | try: 41 | tutorial = Tutorial.objects.get(pk=pk) 42 | except Tutorial.DoesNotExist: 43 | return JsonResponse({'message': 'The tutorial does not exist'}, status=status.HTTP_404_NOT_FOUND) 44 | 45 | if request.method == 'GET': 46 | tutorial_serializer = TutorialSerializer(tutorial) 47 | return JsonResponse(tutorial_serializer.data) 48 | 49 | elif request.method == 'PUT': 50 | tutorial_data = JSONParser().parse(request) 51 | tutorial_serializer = TutorialSerializer(tutorial, data=tutorial_data) 52 | if tutorial_serializer.is_valid(): 53 | tutorial_serializer.save() 54 | return JsonResponse(tutorial_serializer.data) 55 | return JsonResponse(tutorial_serializer.errors, status=status.HTTP_400_BAD_REQUEST) 56 | 57 | elif request.method == 'DELETE': 58 | tutorial.delete() 59 | return JsonResponse({'message': 'Tutorial was deleted successfully!'}, status=status.HTTP_204_NO_CONTENT) 60 | 61 | 62 | @api_view(['GET']) 63 | def tutorial_list_published(request): 64 | tutorials = Tutorial.objects.filter(published=True) 65 | 66 | if request.method == 'GET': 67 | tutorials_serializer = TutorialSerializer(tutorials, many=True) 68 | return JsonResponse(tutorials_serializer.data, safe=False) 69 | 70 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Django Restful CRUD API with MongoDB example 2 | 3 | For more detail, please visit: 4 | > [Django & MongoDB CRUD example with Rest Framework](https://bezkoder.com/django-mongodb-crud-rest-framework/) 5 | 6 | ## Running the Application 7 | 8 | Create the DB tables first: 9 | ``` 10 | python manage.py migrate 11 | ``` 12 | Run the development web server: 13 | ``` 14 | python manage.py runserver 8080 15 | ``` 16 | Open the URL http://localhost:8080/ to access the application. --------------------------------------------------------------------------------