Browse Source

+ change categoryUpsert

ilya_shyian 2 years ago
parent
commit
1829a06821
4 changed files with 124 additions and 231 deletions
  1. 20 2
      store_back/apps/categories/views.py
  2. 0 179
      store_back/settings copy.py
  3. 90 34
      store_back/settings.py
  4. 14 16
      store_back/urls.py

+ 20 - 2
store_back/apps/categories/views.py

@@ -3,6 +3,7 @@ from django.views.decorators.csrf import csrf_exempt
 from rest_framework.parsers import JSONParser
 from .models import Category
 from .serializers import CategorySerializer
+from goods.serializers import GoodSerializer
 import json
 from rest_framework.decorators import api_view, permission_classes,authentication_classes
 from rest_framework.permissions import IsAdminUser,IsAdminUser
@@ -73,9 +74,20 @@ def category_upsert(request):
         goods = json.loads(request.POST.get("goods","[]"))
     except:
         return JsonResponse({"errors":[{"message":"Не вірні дані"}]}, safe=False)
+
+
     if _id :
+
         try:
             category = Category.objects.get(_id = _id)
+            default_goods =json.dumps(list( GoodSerializer(category.goods.all(),many=True).data))
+            default_categories = json.dumps(list(CategorySerializer(category.subcategories.all(),many=True).data))
+            name = request.POST.get("name", category.name)
+            subcategories =  json.loads(request.POST.get("subcategories",default_categories ))
+            parent = request.POST.get("parent", category.parent)
+            goods = json.loads(request.POST.get("goods", default_goods))
+
+
         except Exception as e:
             return JsonResponse({"errors":[{"message":"Не вірні дані"}]}, safe=False)
 
@@ -85,8 +97,14 @@ def category_upsert(request):
         category = Category.objects.create(name=name)
 
     if parent:
-        print(parent)
-        category.parent = Category.objects.get(_id=json.loads(parent)["_id"])
+        if  type(parent) is str:
+            if parent == "null":
+                category.parent = None
+            else:
+                category.parent = Category.objects.get(_id=json.loads(parent)["_id"])
+        else:
+            category.parent = Category.objects.get(_id=parent._id)
+
 
     category.goods.clear()
     for good in goods:

+ 0 - 179
store_back/settings copy.py

@@ -1,179 +0,0 @@
-
-
-import os,sys
-from datetime import timedelta
-
-# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
-BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
-PROJECT_ROOT = os.path.dirname(__file__)
-sys.path.insert(0,os.path.join(PROJECT_ROOT,'apps'))
-
-AUTH_USER_MODEL = 'authAPI.CustomUser'
-
-try:
-    if os.environ['debug'] == 'False':
-        DEBUG = False
-    else:
-        DEBUG = True
-except:
-    DEBUG = True
-
-
-
-
-if DEBUG:
-    SECRET_KEY = 'django-insecure-e*vqkvk_c%y&(v-^isb_%uwxq#y4eun3xhf4al_5f_)&14e5f0'
-else:
-    try:
-        SECRET_KEY = os.environ["SECRET_KEY"]
-    except KeyError as e:
-        raise RuntimeError("Could not find a SECRET_KEY in environment") from e
-    from .prod import *
-
-
-# Application definition
-
-INSTALLED_APPS = [
-    'django.contrib.admin',
-    'django.contrib.auth',
-    'django.contrib.contenttypes',
-    'django.contrib.sessions',
-    'django.contrib.messages',
-    'django.contrib.staticfiles',
-    'rest_framework',
-    'goods.apps.GoodsConfig',
-    'authAPI.apps.AuthAPIConfig',
-    'orders.apps.OrdersConfig',
-    'categories.apps.CategoriesConfig',
-]
-
-MIDDLEWARE = [
-    'django.middleware.security.SecurityMiddleware',
-    'django.contrib.sessions.middleware.SessionMiddleware',
-    'django.middleware.common.CommonMiddleware',
-    'django.middleware.csrf.CsrfViewMiddleware',
-    'django.contrib.auth.middleware.AuthenticationMiddleware',
-    'django.contrib.messages.middleware.MessageMiddleware',
-    'django.middleware.clickjacking.XFrameOptionsMiddleware',
-]
-
-ROOT_URLCONF = 'store_back.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 = 'store_back.wsgi.application'
-
-
-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.0/topics/i18n/
-
-LANGUAGE_CODE = 'en-us'
-
-TIME_ZONE = 'UTC'
-
-USE_I18N = True
-
-USE_TZ = True
-
-DATABASES = {
-    'default': {
-        'ENGINE': 'django.db.backends.postgresql_psycopg2',
-        'NAME': 'dfi11snf6cpamj',
-        'USER' : 'qvkowaptdjfexz',
-        'PASSWORD' : '3ef6f3a16c918da406cd2b388042a45080ff7f9dd10d5f9cc1df0ec0eca8ab7a',
-        'HOST' : 'ec2-52-48-159-67.eu-west-1.compute.amazonaws.com',
-        'PORT' : '5432',
-    }
-}
-
-
-
-
-
-# Static files (CSS, JavaScript, Images)
-# https://docs.djangoproject.com/en/4.0/howto/static-files/
-
-STATIC_ROOT = os.path.join(BASE_DIR, 'static')
-STATIC_URL = 'api/static/'
-
-MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')
-MEDIA_URL = 'api/media/'
-
-
-# Default primary key field type
-# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
-
-DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
-
-
-
-SIMPLE_JWT = {
-    'ACCESS_TOKEN_LIFETIME': timedelta(days=30),
-    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
-    'ROTATE_REFRESH_TOKENS': False,
-    'BLACKLIST_AFTER_ROTATION': False,
-    'UPDATE_LAST_LOGIN': False,
-
-    'ALGORITHM': 'HS256',
-    'SIGNING_KEY': SECRET_KEY,
-    'VERIFYING_KEY': None,
-    'AUDIENCE': None,
-    'ISSUER': None,
-    'JWK_URL': None,
-    'LEEWAY': 0,
-
-    'AUTH_HEADER_TYPES': ('Bearer',),
-    'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
-    'USER_ID_FIELD': '_id',
-    'USER_ID_CLAIM': 'user_id',
-    'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule',
-
-    'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
-    'TOKEN_TYPE_CLAIM': 'token_type',
-    'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser',
-
-    'JTI_CLAIM': 'jti',
-
-    'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
-    'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
-    'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
-}
-
-
-REST_FRAMEWORK = {
-    'DEFAULT_AUTHENTICATION_CLASSES': (
-        'rest_framework_simplejwt.authentication.JWTAuthentication',
-    )
-}
-
-

+ 90 - 34
store_back/settings.py

@@ -1,31 +1,34 @@
-"""
-Django settings for store_back project.
 
-Generated by 'django-admin startproject' using Django 4.0.4.
 
-For more information on this file, see
-https://docs.djangoproject.com/en/4.0/topics/settings/
+import os,sys
+from datetime import timedelta
 
-For the full list of settings and their values, see
-https://docs.djangoproject.com/en/4.0/ref/settings/
-"""
+# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
+BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+PROJECT_ROOT = os.path.dirname(__file__)
+sys.path.insert(0,os.path.join(PROJECT_ROOT,'apps'))
 
-from pathlib import Path
+AUTH_USER_MODEL = 'authAPI.CustomUser'
 
-# Build paths inside the project like this: BASE_DIR / 'subdir'.
-BASE_DIR = Path(__file__).resolve().parent.parent
+try:
+    if os.environ['debug'] == 'False':
+        DEBUG = False
+    else:
+        DEBUG = True
+except:
+    DEBUG = True
 
 
-# Quick-start development settings - unsuitable for production
-# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
 
-# SECURITY WARNING: keep the secret key used in production secret!
-SECRET_KEY = 'django-insecure-@&mo#&9)pe=y_r#4i+teev4_u*_4p-#$6(z9gdtzzt0vw6mdw9'
 
-# SECURITY WARNING: don't run with debug turned on in production!
-DEBUG = True
-
-ALLOWED_HOSTS = []
+if DEBUG:
+    SECRET_KEY = 'django-insecure-e*vqkvk_c%y&(v-^isb_%uwxq#y4eun3xhf4al_5f_)&14e5f0'
+else:
+    try:
+        SECRET_KEY = os.environ["SECRET_KEY"]
+    except KeyError as e:
+        raise RuntimeError("Could not find a SECRET_KEY in environment") from e
+    from .prod import *
 
 
 # Application definition
@@ -37,6 +40,11 @@ INSTALLED_APPS = [
     'django.contrib.sessions',
     'django.contrib.messages',
     'django.contrib.staticfiles',
+    'rest_framework',
+    'goods.apps.GoodsConfig',
+    'authAPI.apps.AuthAPIConfig',
+    'orders.apps.OrdersConfig',
+    'categories.apps.CategoriesConfig',
 ]
 
 MIDDLEWARE = [
@@ -70,20 +78,6 @@ TEMPLATES = [
 WSGI_APPLICATION = 'store_back.wsgi.application'
 
 
-# Database
-# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
-
-DATABASES = {
-    'default': {
-        'ENGINE': 'django.db.backends.sqlite3',
-        'NAME': BASE_DIR / 'db.sqlite3',
-    }
-}
-
-
-# Password validation
-# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
-
 AUTH_PASSWORD_VALIDATORS = [
     {
         'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
@@ -111,13 +105,75 @@ USE_I18N = True
 
 USE_TZ = True
 
+DATABASES = {
+    'default': {
+        'ENGINE': 'django.db.backends.postgresql_psycopg2',
+        'NAME': 'dfi11snf6cpamj',
+        'USER' : 'qvkowaptdjfexz',
+        'PASSWORD' : '3ef6f3a16c918da406cd2b388042a45080ff7f9dd10d5f9cc1df0ec0eca8ab7a',
+        'HOST' : 'ec2-52-48-159-67.eu-west-1.compute.amazonaws.com',
+        'PORT' : '5432',
+    }
+}
+
+
+
+
 
 # Static files (CSS, JavaScript, Images)
 # https://docs.djangoproject.com/en/4.0/howto/static-files/
 
-STATIC_URL = 'static/'
+STATIC_ROOT = os.path.join(BASE_DIR, 'static')
+STATIC_URL = 'api/static/'
+
+MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')
+MEDIA_URL = 'api/media/'
+
 
 # Default primary key field type
 # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
 
 DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
+
+
+
+SIMPLE_JWT = {
+    'ACCESS_TOKEN_LIFETIME': timedelta(days=30),
+    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
+    'ROTATE_REFRESH_TOKENS': False,
+    'BLACKLIST_AFTER_ROTATION': False,
+    'UPDATE_LAST_LOGIN': False,
+
+    'ALGORITHM': 'HS256',
+    'SIGNING_KEY': SECRET_KEY,
+    'VERIFYING_KEY': None,
+    'AUDIENCE': None,
+    'ISSUER': None,
+    'JWK_URL': None,
+    'LEEWAY': 0,
+
+    'AUTH_HEADER_TYPES': ('Bearer',),
+    'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
+    'USER_ID_FIELD': '_id',
+    'USER_ID_CLAIM': 'user_id',
+    'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule',
+
+    'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
+    'TOKEN_TYPE_CLAIM': 'token_type',
+    'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser',
+
+    'JTI_CLAIM': 'jti',
+
+    'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
+    'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
+    'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
+}
+
+
+REST_FRAMEWORK = {
+    'DEFAULT_AUTHENTICATION_CLASSES': (
+        'rest_framework_simplejwt.authentication.JWTAuthentication',
+    )
+}
+
+

+ 14 - 16
store_back/urls.py

@@ -1,21 +1,19 @@
-"""store_back URL Configuration
 
-The `urlpatterns` list routes URLs to views. For more information please see:
-    https://docs.djangoproject.com/en/4.0/topics/http/urls/
-Examples:
-Function views
-    1. Add an import:  from my_app import views
-    2. Add a URL to urlpatterns:  path('', views.home, name='home')
-Class-based views
-    1. Add an import:  from other_app.views import Home
-    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
-Including another URLconf
-    1. Import the include() function: from django.urls import include, path
-    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
-"""
 from django.contrib import admin
-from django.urls import path
+from django.urls import path, include
+from django.conf.urls.static import static
+from django.conf import settings
+
+
 
 urlpatterns = [
-    path('admin/', admin.site.urls),
+    path('api/', include('goods.urls')),
+    path('api/', include('orders.urls')),
+    path('api/', include('categories.urls')),
+    path('api/auth/',include('authAPI.urls')),
+    path('api/admin/', admin.site.urls),
+
 ]
+
+
+urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)