Skip to content

Commit

Permalink
Committed
Browse files Browse the repository at this point in the history
  • Loading branch information
Sumitwarrior7 committed May 19, 2023
0 parents commit 65eec95
Show file tree
Hide file tree
Showing 49 changed files with 30,718 additions and 0 deletions.
1 change: 1 addition & 0 deletions backend/django_backend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
backend.env
Empty file.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
8 changes: 8 additions & 0 deletions backend/django_backend/django_app/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from django.contrib import admin
from . import models


# Register your models here.
admin.site.register(models.Note)


6 changes: 6 additions & 0 deletions backend/django_backend/django_app/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class DjangoAppConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "django_app"
30 changes: 30 additions & 0 deletions backend/django_backend/django_app/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Generated by Django 4.2.1 on 2023-05-16 15:59

from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = []

operations = [
migrations.CreateModel(
name="Note",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("body", models.TextField(blank=True, null=True)),
("updated", models.DateTimeField(auto_now=True)),
("created", models.DateTimeField(auto_now_add=True)),
],
),
]
Empty file.
Binary file not shown.
Binary file not shown.
41 changes: 41 additions & 0 deletions backend/django_backend/django_app/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
from django.db import models


class Note(models.Model):
body = models.TextField(null=True, blank=True)
updated = models.DateTimeField(auto_now=True) #auto_now means to take the current time
created = models.DateTimeField(auto_now_add=True) #auto_now_add means to take that time when actuallt the model instance was created

def _str_(self):
return self.body[0:50]































10 changes: 10 additions & 0 deletions backend/django_backend/django_app/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from rest_framework import serializers
from . import models


class NoteSerializer (serializers.ModelSerializer):
class Meta:
model = models.Note
fields = "__all__"


3 changes: 3 additions & 0 deletions backend/django_backend/django_app/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
11 changes: 11 additions & 0 deletions backend/django_backend/django_app/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from django.urls import path
from . import views


urlpatterns = [
path("notes/", views.GetNotes),
path("note/<int:note_id>/", views.GetNote),
path("note/create/", views.CreateNote),
path("note/update/<int:note_id>/", views.UpdateNote),
path("note/delete/<int:note_id>/", views.DeleteNote),
]
62 changes: 62 additions & 0 deletions backend/django_backend/django_app/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.decorators import api_view
from django.http import JsonResponse
from django.core.exceptions import ObjectDoesNotExist
from . import models
from . import serializers
from django.http import QueryDict


@api_view(["GET"])
def GetNotes(request):
notes = models.Note.objects.all()
serializer = serializers.NoteSerializer(notes, many=True)
return Response(serializer.data)


@api_view(["GET"])
def GetNote(request, note_id):
try:
note = models.Note.objects.get(id=note_id)
except ObjectDoesNotExist:
error_message = "Note not found"
return JsonResponse({'error': error_message}, status=404)
else:
serializer = serializers.NoteSerializer(note)
return Response(serializer.data)


@api_view(["POST"])
def CreateNote(request):
data = request.data
print(data)
created_note = models.Note.objects.create(body=data["body"])
serializer = serializers.NoteSerializer(created_note, many=False)
return Response(serializer.data)

@api_view(["PUT"])
def UpdateNote(request, note_id):
try:
note = models.Note.objects.get(id=note_id)
print("Note, i want to edit", note)
except ObjectDoesNotExist:
error_message = "Note not found"
return JsonResponse({'error': error_message}, status=404)
else:
new_data = request.data
# Here in serializer, first argument is a model instance, and second argument is a dictionary <{body:"updated body value"}> we are getting from frontend
serializer = serializers.NoteSerializer(instance=note, data=new_data)
print("Serializer :", serializer)
if serializer.is_valid():
serializer.save()

return Response(serializer.data)


@api_view(["DELETE"])
def DeleteNote(request, note_id):
note = models.Note.objects.get(id=note_id)
print(note)
note.delete()
return Response("Note was deleted")
Empty file.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
16 changes: 16 additions & 0 deletions backend/django_backend/django_backend/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
ASGI config for django_backend project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_backend.settings")

application = get_asgi_application()
152 changes: 152 additions & 0 deletions backend/django_backend/django_backend/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
"""
Django settings for django_backend project.
Generated by 'django-admin startproject' using Django 4.2.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""

from pathlib import Path
import os

# For creating environment variables for confidential stuffs
import dotenv
dotenv.load_dotenv()

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-4wl5zi-b1na2u*^=a+vzs+%08w0kxi33lb419p1s5875ffa97-"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*'] # for CORS


# Application definition

INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"django_app",
"rest_framework",
'corsheaders',
]

MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"corsheaders.middleware.CorsMiddleware", # For CORS
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "django_backend.urls"

TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]

WSGI_APPLICATION = "django_backend.wsgi.application"


# It is necessary to install mysqlclient package to establish the connection between the MySQL and Django.
# pip install mysqlclient
# In order to create new db-file in mysql use CLI "CREATE DATABASE db_name;"
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'my_db',
'USER': 'root',
'PASSWORD': os.getenv('MYSQL_PASSWORD'),
'HOST': 'localhost',
'PORT': '3306',
'OPTIONS': {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"
}
}
}


# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",},
{"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",},
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",},
]


# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/

STATIC_URL = "static/"

# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

''' CORS policy '''
CORS_ORIGIN_ALLOW_ALL = True
#
# CORS_ALLOWED_ORIGINS = [
# # Add the origin of your React app
# 'http://localhost:3000',
# ]
#
# CORS_ALLOW_METHODS = [
# 'DELETE',
# 'GET',
# 'OPTIONS',
# 'PATCH',
# 'POST',
# 'PUT',
# ]


8 changes: 8 additions & 0 deletions backend/django_backend/django_backend/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from django.contrib import admin
from django.urls import path, include


urlpatterns = [
path("admin/", admin.site.urls),
path('api/', include('django_app.urls')),
]
16 changes: 16 additions & 0 deletions backend/django_backend/django_backend/wsgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
WSGI config for django_backend project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_backend.settings")

application = get_wsgi_application()
Loading

0 comments on commit 65eec95

Please sign in to comment.