├── .gitignore
├── DjangoRestApisPostgreSQL
├── .project
├── .pydevproject
├── DjangoRestApisPostgreSQL
│ ├── __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
--------------------------------------------------------------------------------
/DjangoRestApisPostgreSQL/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | DjangoRestApisPostgreSQL
4 |
5 |
6 |
7 |
8 |
9 | org.python.pydev.PyDevBuilder
10 |
11 |
12 |
13 |
14 |
15 | org.python.pydev.pythonNature
16 |
17 |
18 |
--------------------------------------------------------------------------------
/DjangoRestApisPostgreSQL/.pydevproject:
--------------------------------------------------------------------------------
1 |
2 |
3 | Default
4 | python interpreter
5 |
6 |
--------------------------------------------------------------------------------
/DjangoRestApisPostgreSQL/DjangoRestApisPostgreSQL/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bezkoder/django-rest-api-postgresql/83bb7ef192ee8445c9b4478b936428a68dd8cdc7/DjangoRestApisPostgreSQL/DjangoRestApisPostgreSQL/__init__.py
--------------------------------------------------------------------------------
/DjangoRestApisPostgreSQL/DjangoRestApisPostgreSQL/settings.py:
--------------------------------------------------------------------------------
1 | """
2 | Django settings for DjangoRestApisPostgreSQL 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 = 'w-k7xx44*y)tq&@b5=9bniqw_q486rywjacy4+vo_**94lh=bd'
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 | # Tutorials application
43 | 'tutorials.apps.TutorialsConfig',
44 | # CORS
45 | 'corsheaders',
46 | ]
47 |
48 | MIDDLEWARE = [
49 | 'django.middleware.security.SecurityMiddleware',
50 | 'django.contrib.sessions.middleware.SessionMiddleware',
51 | 'django.middleware.csrf.CsrfViewMiddleware',
52 | 'django.contrib.auth.middleware.AuthenticationMiddleware',
53 | 'django.contrib.messages.middleware.MessageMiddleware',
54 | 'django.middleware.clickjacking.XFrameOptionsMiddleware',
55 | # CORS
56 | 'corsheaders.middleware.CorsMiddleware',
57 | 'django.middleware.common.CommonMiddleware',
58 | ]
59 |
60 | CORS_ORIGIN_ALLOW_ALL = False
61 | CORS_ORIGIN_WHITELIST = (
62 | 'http://localhost:8081',
63 | )
64 |
65 | ROOT_URLCONF = 'DjangoRestApisPostgreSQL.urls'
66 |
67 | TEMPLATES = [
68 | {
69 | 'BACKEND': 'django.template.backends.django.DjangoTemplates',
70 | 'DIRS': [],
71 | 'APP_DIRS': True,
72 | 'OPTIONS': {
73 | 'context_processors': [
74 | 'django.template.context_processors.debug',
75 | 'django.template.context_processors.request',
76 | 'django.contrib.auth.context_processors.auth',
77 | 'django.contrib.messages.context_processors.messages',
78 | ],
79 | },
80 | },
81 | ]
82 |
83 | WSGI_APPLICATION = 'DjangoRestApisPostgreSQL.wsgi.application'
84 |
85 |
86 | # Database
87 | # https://docs.djangoproject.com/en/2.1/ref/settings/#databases
88 |
89 | DATABASES = {
90 | 'default': {
91 | 'ENGINE': 'django.db.backends.postgresql',
92 | 'NAME': 'testdb',
93 | 'USER': 'postgres',
94 | 'PASSWORD': '123',
95 | 'HOST': '127.0.0.1',
96 | 'PORT': '5432',
97 | }
98 | }
99 |
100 |
101 | # Password validation
102 | # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
103 |
104 | AUTH_PASSWORD_VALIDATORS = [
105 | {
106 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
107 | },
108 | {
109 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
110 | },
111 | {
112 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
113 | },
114 | {
115 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
116 | },
117 | ]
118 |
119 |
120 | # Internationalization
121 | # https://docs.djangoproject.com/en/2.1/topics/i18n/
122 |
123 | LANGUAGE_CODE = 'en-us'
124 |
125 | TIME_ZONE = 'UTC'
126 |
127 | USE_I18N = True
128 |
129 | USE_L10N = True
130 |
131 | USE_TZ = True
132 |
133 |
134 | # Static files (CSS, JavaScript, Images)
135 | # https://docs.djangoproject.com/en/2.1/howto/static-files/
136 |
137 | STATIC_URL = '/static/'
138 |
--------------------------------------------------------------------------------
/DjangoRestApisPostgreSQL/DjangoRestApisPostgreSQL/urls.py:
--------------------------------------------------------------------------------
1 | from django.conf.urls import url, include
2 |
3 | urlpatterns = [
4 | url(r'^', include('tutorials.urls')),
5 | ]
6 |
--------------------------------------------------------------------------------
/DjangoRestApisPostgreSQL/DjangoRestApisPostgreSQL/wsgi.py:
--------------------------------------------------------------------------------
1 | """
2 | WSGI config for DjangoRestApisPostgreSQL 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', 'DjangoRestApisPostgreSQL.settings')
15 |
16 | application = get_wsgi_application()
17 |
--------------------------------------------------------------------------------
/DjangoRestApisPostgreSQL/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', 'DjangoRestApisPostgreSQL.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 |
--------------------------------------------------------------------------------
/DjangoRestApisPostgreSQL/tutorials/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bezkoder/django-rest-api-postgresql/83bb7ef192ee8445c9b4478b936428a68dd8cdc7/DjangoRestApisPostgreSQL/tutorials/__init__.py
--------------------------------------------------------------------------------
/DjangoRestApisPostgreSQL/tutorials/admin.py:
--------------------------------------------------------------------------------
1 | from django.contrib import admin
2 |
3 | # Register your models here.
4 |
--------------------------------------------------------------------------------
/DjangoRestApisPostgreSQL/tutorials/apps.py:
--------------------------------------------------------------------------------
1 | from django.apps import AppConfig
2 |
3 |
4 | class TutorialsConfig(AppConfig):
5 | name = 'tutorials'
6 |
--------------------------------------------------------------------------------
/DjangoRestApisPostgreSQL/tutorials/migrations/0001_initial.py:
--------------------------------------------------------------------------------
1 | # Generated by Django 2.1.15 on 2020-05-08 02: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='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 |
--------------------------------------------------------------------------------
/DjangoRestApisPostgreSQL/tutorials/migrations/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bezkoder/django-rest-api-postgresql/83bb7ef192ee8445c9b4478b936428a68dd8cdc7/DjangoRestApisPostgreSQL/tutorials/migrations/__init__.py
--------------------------------------------------------------------------------
/DjangoRestApisPostgreSQL/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 |
--------------------------------------------------------------------------------
/DjangoRestApisPostgreSQL/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 |
--------------------------------------------------------------------------------
/DjangoRestApisPostgreSQL/tutorials/tests.py:
--------------------------------------------------------------------------------
1 | from django.test import TestCase
2 |
3 | # Create your tests here.
4 |
--------------------------------------------------------------------------------
/DjangoRestApisPostgreSQL/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 |
--------------------------------------------------------------------------------
/DjangoRestApisPostgreSQL/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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Django Restful CRUD API with PostgreSQL example
2 |
3 | For more detail, please visit:
4 | > [Django CRUD with PostgreSQL example | Django Rest Framework](https://bezkoder.com/django-postgresql-crud-rest-framework/)
5 |
6 | Full-stack CRUD App:
7 | > [Django + Vue.js](https://bezkoder.com/django-vue-js-rest-framework/)
8 |
9 | > [Django + React.js](https://bezkoder.com/django-react-axios-rest-framework/)
10 |
11 | > [Django + Angular](https://bezkoder.com/django-angular-postgresql/)
12 |
13 | ## Running the Application
14 |
15 | Create the DB tables first:
16 | ```
17 | python manage.py migrate
18 | ```
19 | Run the development web server:
20 | ```
21 | python manage.py runserver 8080
22 | ```
23 | Open the URL http://localhost:8080/ to access the application.
--------------------------------------------------------------------------------