Skip to content

Commit 7d5f53a

Browse files
committed
Django CRUD Application with MongoDB database using Django Rest Framework and Djongo
1 parent 48b3929 commit 7d5f53a

File tree

14 files changed

+415
-0
lines changed

14 files changed

+415
-0
lines changed

Django/Django-MongoDB-Djongo-CRUD-Example/customers/__init__.py

Whitespace-only changes.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
from django.contrib import admin
2+
3+
# Register your models here.
4+
from customers.models import Customer
5+
6+
# Register your models here.
7+
admin.site.register(Customer)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
from django.apps import AppConfig
2+
3+
4+
class CustomersConfig(AppConfig):
5+
name = 'customers'
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
from djongo import models
2+
3+
class Customer(models.Model):
4+
firstname = models.CharField(max_length=70, blank=False, default='')
5+
lastname = models.CharField(max_length=70, blank=False, default='')
6+
age = models.IntegerField(blank=False, default=1)
7+
address = models.CharField(max_length=70, blank=False, default='')
8+
copyrightby = models.CharField(max_length=70, blank=False, default='')
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
from rest_framework import serializers
2+
from customers.models import Customer
3+
4+
class CustomerSerializer(serializers.ModelSerializer):
5+
6+
class Meta:
7+
model = Customer
8+
fields = ('id',
9+
'firstname',
10+
'lastname',
11+
'age',
12+
'address',
13+
'copyrightby')
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
from django.test import TestCase
2+
3+
# Create your tests here.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
from django.conf.urls import url
2+
from customers import views
3+
4+
urlpatterns = [
5+
url(r'^customers/$', views.customer_list),
6+
url(r'^customers/(?P<pk>[0-9]+)$', views.customer_detail),
7+
url(r'^customers/age/(?P<age>[0-9]+)/$', views.customer_list_age),
8+
]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
from django.shortcuts import render
2+
from django.http import HttpResponse
3+
from django.http.response import JsonResponse
4+
from django.views.decorators.csrf import csrf_exempt
5+
from rest_framework.parsers import JSONParser
6+
from rest_framework import status
7+
8+
from customers.models import Customer
9+
from customers.serializers import CustomerSerializer
10+
11+
from rest_framework.decorators import api_view
12+
13+
@csrf_exempt
14+
@api_view(['GET', 'POST', 'DELETE'])
15+
def customer_list(request):
16+
if request.method == 'GET':
17+
try:
18+
customers = Customer.objects.all()
19+
customers_serializer = CustomerSerializer(customers, many=True)
20+
21+
response = {
22+
'message': "Get all Customers'Infos Successfully",
23+
'customers': customers_serializer.data,
24+
'error': ""
25+
}
26+
return JsonResponse(response, status=status.HTTP_200_OK);
27+
except:
28+
error = {
29+
'message': "Fail! -> can NOT get all the customers List. Please check again!",
30+
'customers': "[]",
31+
'error': "Error"
32+
}
33+
return JsonResponse(error, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
34+
35+
elif request.method == 'POST':
36+
try:
37+
customer_data = JSONParser().parse(request)
38+
customer_serializer = CustomerSerializer(data=customer_data)
39+
40+
if customer_serializer.is_valid():
41+
customer_serializer.save()
42+
print(customer_serializer.data)
43+
response = {
44+
'message': "Successfully Upload a Customer with id = %d" % customer_serializer.data.get('id'),
45+
'customers': [customer_serializer.data],
46+
'error': ""
47+
}
48+
return JsonResponse(response, status=status.HTTP_201_CREATED)
49+
else:
50+
error = {
51+
'message':"Can Not upload successfully!",
52+
'customers':"[]",
53+
'error': customer_serializer.errors
54+
}
55+
return JsonResponse(error, status=status.HTTP_400_BAD_REQUEST)
56+
except:
57+
exceptionError = {
58+
'message': "Can Not upload successfully!",
59+
'customers': "[]",
60+
'error': "Having an exception!"
61+
}
62+
return JsonResponse(exceptionError, status=status.HTTP_500_INTERNAL_SERVER_ERROR);
63+
64+
elif request.method == 'DELETE':
65+
try:
66+
Customer.objects.all().delete()
67+
return HttpResponse(status=status.HTTP_204_NO_CONTENT)
68+
except:
69+
exceptionError = {
70+
'message': "Can Not Deleted successfully!",
71+
'customers': "[]",
72+
'error': "Having an exception!"
73+
}
74+
return JsonResponse(exceptionError, status=status.HTTP_500_INTERNAL_SERVER_ERROR);
75+
76+
@csrf_exempt
77+
@api_view(['GET', 'PUT', 'DELETE'])
78+
def customer_detail(request, pk):
79+
try:
80+
customer = Customer.objects.get(pk=pk)
81+
except Customer.DoesNotExist:
82+
exceptionError = {
83+
'message': "Not found a Customer with id = %s!" % pk,
84+
'customers': "[]",
85+
'error': "404 Code - Not Found!"
86+
}
87+
return JsonResponse(exceptionError, status=status.HTTP_404_NOT_FOUND)
88+
89+
if request.method == 'GET':
90+
customer_serializer = CustomerSerializer(customer)
91+
response = {
92+
'message': "Successfully get a Customer with id = %s" % pk,
93+
'customers': [customer_serializer.data],
94+
'error': ""
95+
}
96+
return JsonResponse(response, status=status.HTTP_200_OK);
97+
98+
elif request.method == 'PUT':
99+
try:
100+
customer_data = JSONParser().parse(request)
101+
customer_serializer = CustomerSerializer(customer, data=customer_data)
102+
103+
if customer_serializer.is_valid():
104+
customer_serializer.save()
105+
response = {
106+
'message': "Successfully Update a Customer with id = %s" % pk,
107+
'customers': [customer_serializer.data],
108+
'error': ""
109+
}
110+
return JsonResponse(response)
111+
112+
response = {
113+
'message': "Fail to Update a Customer with id = %s" % pk,
114+
'customers': [customer_serializer.data],
115+
'error': customer_serializer.errors
116+
}
117+
return JsonResponse(response, status=status.HTTP_400_BAD_REQUEST)
118+
except:
119+
exceptionError = {
120+
'message': "Fail to update a Customer with id = %s!" % pk,
121+
'customers': [customer_serializer.data],
122+
'error': "Internal Error!"
123+
}
124+
return JsonResponse(exceptionError, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
125+
126+
elif request.method == 'DELETE':
127+
print("Deleting a Customer with id=%s"%pk)
128+
customer.delete()
129+
customer_serializer = CustomerSerializer(customer)
130+
response = {
131+
'message': "Successfully Delete a Customer with id = %s" % pk,
132+
'customers': [customer_serializer.data],
133+
'error': ""
134+
}
135+
return JsonResponse(response)
136+
137+
@csrf_exempt
138+
@api_view(['GET'])
139+
def customer_list_age(request, age):
140+
try:
141+
customers = Customer.objects.filter(age=age)
142+
143+
if request.method == 'GET':
144+
customers_serializer = CustomerSerializer(customers, many=True)
145+
response = {
146+
'message': "Successfully filter all Customers with age = %s" % age,
147+
'customers': customers_serializer.data,
148+
'error': ""
149+
}
150+
return JsonResponse(response, safe=False)
151+
# In order to serialize objects, we must set 'safe=False'
152+
except:
153+
exceptionError = {
154+
'message': "Fail to get a Customer with age = %s" % age ,
155+
'customers': "[]",
156+
'error': "Raise an Exception!"
157+
}
158+
return JsonResponse(exceptionError, status=status.HTTP_500_INTERNAL_SERVER_ERROR);

Django/Django-MongoDB-Djongo-CRUD-Example/djangoLoiZenAiRestAPIs/__init__.py

Whitespace-only changes.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
"""
2+
ASGI config for djangoLoiZenAiRestAPIs 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.0/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', 'djangoLoiZenAiRestAPIs.settings')
15+
16+
application = get_asgi_application()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
"""
2+
Django settings for djangoLoiZenAiRestAPIs project.
3+
4+
Generated by 'django-admin startproject' using Django 3.0.8.
5+
6+
For more information on this file, see
7+
https://docs.djangoproject.com/en/3.0/topics/settings/
8+
9+
For the full list of settings and their values, see
10+
https://docs.djangoproject.com/en/3.0/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/3.0/howto/deployment/checklist/
21+
22+
# SECURITY WARNING: keep the secret key used in production secret!
23+
SECRET_KEY = 'g_9v1%(32!hn21)#4hnxwfm*hr6e$+=e*3cs&)q12j()_b*k$l'
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+
# Django REST framework
41+
'rest_framework',
42+
# Customers application
43+
'customers.apps.CustomersConfig',
44+
# CORS
45+
'corsheaders',
46+
]
47+
48+
MIDDLEWARE = [
49+
'django.middleware.security.SecurityMiddleware',
50+
'django.contrib.sessions.middleware.SessionMiddleware',
51+
'django.middleware.common.CommonMiddleware',
52+
'django.middleware.csrf.CsrfViewMiddleware',
53+
'django.contrib.auth.middleware.AuthenticationMiddleware',
54+
'django.contrib.messages.middleware.MessageMiddleware',
55+
'django.middleware.clickjacking.XFrameOptionsMiddleware',
56+
# CORS
57+
'corsheaders.middleware.CorsMiddleware',
58+
'django.middleware.common.CommonMiddleware',
59+
]
60+
61+
CORS_ORIGIN_ALLOW_ALL = False
62+
CORS_ORIGIN_WHITELIST = (
63+
'http://localhost:4200',
64+
)
65+
66+
ROOT_URLCONF = 'djangoLoiZenAiRestAPIs.urls'
67+
68+
TEMPLATES = [
69+
{
70+
'BACKEND': 'django.template.backends.django.DjangoTemplates',
71+
'DIRS': [],
72+
'APP_DIRS': True,
73+
'OPTIONS': {
74+
'context_processors': [
75+
'django.template.context_processors.debug',
76+
'django.template.context_processors.request',
77+
'django.contrib.auth.context_processors.auth',
78+
'django.contrib.messages.context_processors.messages',
79+
],
80+
},
81+
},
82+
]
83+
84+
WSGI_APPLICATION = 'djangoLoiZenAiRestAPIs.wsgi.application'
85+
86+
87+
# Password validation
88+
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
89+
90+
AUTH_PASSWORD_VALIDATORS = [
91+
{
92+
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
93+
},
94+
{
95+
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
96+
},
97+
{
98+
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
99+
},
100+
{
101+
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
102+
},
103+
]
104+
105+
106+
# Internationalization
107+
# https://docs.djangoproject.com/en/3.0/topics/i18n/
108+
109+
LANGUAGE_CODE = 'en-us'
110+
111+
TIME_ZONE = 'UTC'
112+
113+
USE_I18N = True
114+
115+
USE_L10N = True
116+
117+
USE_TZ = True
118+
119+
120+
# Static files (CSS, JavaScript, Images)
121+
# https://docs.djangoproject.com/en/3.0/howto/static-files/
122+
123+
STATIC_URL = '/static/'
124+
125+
DATABASES = {
126+
'default': {
127+
'ENGINE': 'djongo',
128+
"CLIENT": {
129+
"name": 'loizenaidb',
130+
"host": 'mongodb+srv://loizenai:loizenai@cluster0.gmd7e.mongodb.net/loizenaidb?retryWrites=true&w=majority',
131+
"username": 'loizenai',
132+
"password": 'loizenai',
133+
"authMechanism": "SCRAM-SHA-1"
134+
}
135+
}
136+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
"""djangoLoiZenAiRestAPIs URL Configuration
2+
3+
The `urlpatterns` list routes URLs to views. For more information please see:
4+
https://docs.djangoproject.com/en/3.0/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+
19+
from django.conf.urls import url, include
20+
21+
urlpatterns = [
22+
url(r'^', include('customers.urls')),
23+
path('admin/', admin.site.urls),
24+
]

0 commit comments

Comments
 (0)