diff --git a/.gitignore b/.gitignore index 894a44cc0..f2b879631 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ + +.env + # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000..adf7e3adf --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "python.pythonPath": "/Library/Frameworks/Python.framework/Versions/3.7/bin/python3" +} \ No newline at end of file diff --git a/Pipfile b/Pipfile new file mode 100644 index 000000000..342459a56 --- /dev/null +++ b/Pipfile @@ -0,0 +1,20 @@ +[[source]] +url = "https://pypi.org/simple" +verify_ssl = true +name = "pypi" + +[packages] +django = "*" +django-admin = "*" +djangorestframework = "*" +django-cors-headers = "*" +gunicorn = "*" +"psycopg2-binary" = "*" +dj-database-url = "*" +python-decouple = "*" +whitenoise = "*" + +[dev-packages] + +[requires] +python_version = "3.7" diff --git a/Pipfile.lock b/Pipfile.lock new file mode 100644 index 000000000..03f7bbcfa --- /dev/null +++ b/Pipfile.lock @@ -0,0 +1,155 @@ +{ + "_meta": { + "hash": { + "sha256": "c76de0645d50c7f12fa44b6136995b3b7209031daeafe7a8117355dddb99dca6" + }, + "pipfile-spec": 6, + "requires": { + "python_version": "3.7" + }, + "sources": [ + { + "name": "pypi", + "url": "https://pypi.org/simple", + "verify_ssl": true + } + ] + }, + "default": { + "dj-database-url": { + "hashes": [ + "sha256:4aeaeb1f573c74835b0686a2b46b85990571159ffc21aa57ecd4d1e1cb334163", + "sha256:851785365761ebe4994a921b433062309eb882fedd318e1b0fcecc607ed02da9" + ], + "index": "pypi", + "version": "==0.5.0" + }, + "django": { + "hashes": [ + "sha256:068d51054083d06ceb32ce02b7203f1854256047a0d58682677dd4f81bceabd7", + "sha256:55409a056b27e6d1246f19ede41c6c610e4cab549c005b62cbeefabc6433356b" + ], + "index": "pypi", + "version": "==2.1.4" + }, + "django-admin": { + "hashes": [ + "sha256:2f507fc822b7af4191bf866b620c8a2d0e6e8641ee66ee32a73233b5eca4d04d", + "sha256:78182b41416b9d6ff469015d438911c64ce4ba210a2242da3c77e6de85c2d86b" + ], + "index": "pypi", + "version": "==1.3.2" + }, + "django-cors-headers": { + "hashes": [ + "sha256:5545009c9b233ea7e70da7dbab7cb1c12afa01279895086f98ec243d7eab46fa", + "sha256:c4c2ee97139d18541a1be7d96fe337d1694623816d83f53cb7c00da9b94acae1" + ], + "index": "pypi", + "version": "==2.4.0" + }, + "django-excel-response2": { + "hashes": [ + "sha256:0239654e95f375e8eab37a655171bd8c8a896b9b80afa41fd05abecd2d057873", + "sha256:a1abe97fb2773910d32ed0a222c20cd6ae8f241025a6b509a424a2b91defb7a2" + ], + "version": "==2.0.8" + }, + "django-six": { + "hashes": [ + "sha256:b05c96f5a7dbdcf9b513748df27421e8d63e586399bac80a928a29d97d78d450", + "sha256:d307483f3591fa3b471a3724659710229ea3127e112499f2b6f7fa7faa1e27e4" + ], + "version": "==1.0.4" + }, + "djangorestframework": { + "hashes": [ + "sha256:607865b0bb1598b153793892101d881466bd5a991de12bd6229abb18b1c86136", + "sha256:63f76cbe1e7d12b94c357d7e54401103b2e52aef0f7c1650d6c820ad708776e5" + ], + "index": "pypi", + "version": "==3.9.0" + }, + "gunicorn": { + "hashes": [ + "sha256:aa8e0b40b4157b36a5df5e599f45c9c76d6af43845ba3b3b0efe2c70473c2471", + "sha256:fa2662097c66f920f53f70621c6c58ca4a3c4d3434205e608e121b5b3b71f4f3" + ], + "index": "pypi", + "version": "==19.9.0" + }, + "psycopg2-binary": { + "hashes": [ + "sha256:036bcb198a7cc4ce0fe43344f8c2c9a8155aefa411633f426c8c6ed58a6c0426", + "sha256:1d770fcc02cdf628aebac7404d56b28a7e9ebec8cfc0e63260bd54d6edfa16d4", + "sha256:1fdc6f369dcf229de6c873522d54336af598b9470ccd5300e2f58ee506f5ca13", + "sha256:21f9ddc0ff6e07f7d7b6b484eb9da2c03bc9931dd13e36796b111d631f7135a3", + "sha256:247873cda726f7956f745a3e03158b00de79c4abea8776dc2f611d5ba368d72d", + "sha256:3aa31c42f29f1da6f4fd41433ad15052d5ff045f2214002e027a321f79d64e2c", + "sha256:475f694f87dbc619010b26de7d0fc575a4accf503f2200885cc21f526bffe2ad", + "sha256:4b5e332a24bf6e2fda1f51ca2a57ae1083352293a08eeea1fa1112dc7dd542d1", + "sha256:570d521660574aca40be7b4d532dfb6f156aad7b16b5ed62d1534f64f1ef72d8", + "sha256:59072de7def0690dd13112d2bdb453e20570a97297070f876fbbb7cbc1c26b05", + "sha256:5f0b658989e918ef187f8a08db0420528126f2c7da182a7b9f8bf7f85144d4e4", + "sha256:649199c84a966917d86cdc2046e03d536763576c0b2a756059ae0b3a9656bc20", + "sha256:6645fc9b4705ae8fbf1ef7674f416f89ae1559deec810f6dd15197dfa52893da", + "sha256:6872dd54d4e398d781efe8fe2e2d7eafe4450d61b5c4898aced7610109a6df75", + "sha256:6ce34fbc251fc0d691c8d131250ba6f42fd2b28ef28558d528ba8c558cb28804", + "sha256:73920d167a0a4d1006f5f3b9a3efce6f0e5e883a99599d38206d43f27697df00", + "sha256:8a671732b87ae423e34b51139628123bc0306c2cb85c226e71b28d3d57d7e42a", + "sha256:8d517e8fda2efebca27c2018e14c90ed7dc3f04d7098b3da2912e62a1a5585fe", + "sha256:9475a008eb7279e20d400c76471843c321b46acacc7ee3de0b47233a1e3fa2cf", + "sha256:96947b8cd7b3148fb0e6549fcb31258a736595d6f2a599f8cd450e9a80a14781", + "sha256:abf229f24daa93f67ac53e2e17c8798a71a01711eb9fcdd029abba8637164338", + "sha256:b1ab012f276df584beb74f81acb63905762c25803ece647016613c3d6ad4e432", + "sha256:b22b33f6f0071fe57cb4e9158f353c88d41e739a3ec0d76f7b704539e7076427", + "sha256:b3b2d53274858e50ad2ffdd6d97ce1d014e1e530f82ec8b307edd5d4c921badf", + "sha256:bab26a729befc7b9fab9ded1bba9c51b785188b79f8a2796ba03e7e734269e2e", + "sha256:daa1a593629aa49f506eddc9d23dc7f89b35693b90e1fbcd4480182d1203ea90", + "sha256:dd111280ce40e89fd17b19c1269fd1b74a30fce9d44a550840e86edb33924eb8", + "sha256:e0b86084f1e2e78c451994410de756deba206884d6bed68d5a3d7f39ff5fea1d", + "sha256:eb86520753560a7e89639500e2a254bb6f683342af598088cb72c73edcad21e6", + "sha256:ff18c5c40a38d41811c23e2480615425c97ea81fd7e9118b8b899c512d97c737" + ], + "index": "pypi", + "version": "==2.7.6.1" + }, + "python-decouple": { + "hashes": [ + "sha256:1317df14b43efee4337a4aa02914bf004f010cd56d6c4bd894e6474ec8c4fe2d" + ], + "index": "pypi", + "version": "==3.1" + }, + "pytz": { + "hashes": [ + "sha256:31cb35c89bd7d333cd32c5f278fca91b523b0834369e757f4c5641ea252236ca", + "sha256:8e0f8568c118d3077b46be7d654cc8167fa916092e28320cde048e54bfc9f1e6" + ], + "version": "==2018.7" + }, + "screen": { + "hashes": [ + "sha256:29009e0306d005679cc43c8cd69856a046265433310c10e71920591de3c58fda", + "sha256:aebfe90de7b8a646d4f3c2b214bd6ffa2ab12ed9d0b14c08620d9c7f7b8ee670" + ], + "version": "==1.0.1" + }, + "whitenoise": { + "hashes": [ + "sha256:118ab3e5f815d380171b100b05b76de2a07612f422368a201a9ffdeefb2251c1", + "sha256:42133ddd5229eeb6a0c9899496bdbe56c292394bf8666da77deeb27454c0456a" + ], + "index": "pypi", + "version": "==4.1.2" + }, + "xlwt": { + "hashes": [ + "sha256:a082260524678ba48a297d922cc385f58278b8aa68741596a87de01a9c628b2e", + "sha256:c59912717a9b28f1a3c2a98fd60741014b06b043936dcecbc113eaaada156c88" + ], + "version": "==1.3.0" + } + }, + "develop": {} +} diff --git a/Procfile b/Procfile new file mode 100644 index 000000000..890cbf6e7 --- /dev/null +++ b/Procfile @@ -0,0 +1 @@ +web: gunicorn djorg.wsgi --log-file - diff --git a/djadmin.py b/djadmin.py new file mode 100644 index 000000000..0b7bce6f0 --- /dev/null +++ b/djadmin.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- + +import six +from django.conf import settings +from django.contrib import admin +from django.contrib.admin.utils import model_format_dict +from django.db.models.fields import BLANK_CHOICE_DASH +from django.utils.timezone import template_localtime +from django.utils.translation import ugettext_lazy as _ +from excel_response2 import ExcelResponse + + +if not hasattr(settings, 'DJANGO_ADMIN_DISABLE_DELETE_SELECTED') or settings.DJANGO_ADMIN_DISABLE_DELETE_SELECTED: + admin.site.disable_action('delete_selected') + + +class AdvancedActionsModelAdmin(object): + def get_action_choices(self, request, default_choices=BLANK_CHOICE_DASH): + """ + Return a list of choices for use in a form object. Each choice is a tuple (name, description). + """ + actions_exclude = self.actions_exclude if hasattr(self, 'actions_exclude') else [] + choices = [] + default_choices + for func, name, description in six.itervalues(self.get_actions(request)): + if name in actions_exclude: + continue + choice = (name, description % model_format_dict(self.opts)) + choices.append(choice) + return choices + + +class DeleteModelAdmin(object): + actions = ['override_delete_selected'] + + def override_delete_selected(modeladmin, request, queryset): + for query in queryset: + modeladmin.delete_model(request, query) + + override_delete_selected.short_description = _(u'Delete selected %(verbose_name_plural)s') + + +class ExportExcelModelAdmin(object): + actions = ['export_excel'] + + def export_excel(modeladmin, request, queryset): + force_csv = (hasattr(settings, 'DJANGO_EXCEL_RESPONSE') and settings.DJANGO_EXCEL_RESPONSE) or (hasattr(modeladmin, 'force_csv') and modeladmin.force_csv) + return ExcelResponse(queryset, output_name=modeladmin.model._meta.verbose_name_plural, force_csv=force_csv) + + export_excel.short_description = _(u'Export selected %(verbose_name_plural)s as Excel') + + +class AdvancedExportExcelModelAdmin(object): + actions = ['advanced_export_excel'] + + def excel_item(modeladmin, query, field): + foo_field = 'get_{0}_display'.format(field) + return unicode(getattr(query, foo_field)() if hasattr(query, foo_field) else template_localtime(getattr(query, field))) + + def excel_data(modeladmin, request, query, model_fields, has_extra_excel_fields): + excel_item = [modeladmin.excel_item(query, field) for field in model_fields] + return excel_item + list(modeladmin.add_extra_excel_fields(request, query)) if has_extra_excel_fields else excel_item + + def advanced_export_excel(modeladmin, request, queryset): + has_excel_headers = hasattr(modeladmin, 'excel_headers') + has_excel_headers_mapping = hasattr(modeladmin, 'excel_headers_mapping') + has_excel_fields = hasattr(modeladmin, 'excel_fields') + has_excel_fields_exclude = hasattr(modeladmin, 'excel_fields_exclude') + has_extra_excel_fields = hasattr(modeladmin, 'extra_excel_fields') # Add by call add_extra_excel_fields + + model_fields = list(modeladmin.excel_fields) if has_excel_fields else [f.name for f in modeladmin.model._meta.fields] + if has_excel_fields_exclude: + model_fields = [field for field in model_fields if field not in set(modeladmin.excel_fields_exclude)] + + excel_headers = modeladmin.excel_headers if has_excel_headers else (model_fields + list(modeladmin.extra_excel_fields) if has_extra_excel_fields else model_fields) + excel_headers = [(modeladmin.excel_headers_mapping.get(header) or header) for header in excel_headers] if has_excel_headers_mapping else excel_headers + + excel_data = [excel_headers] + excel_data += [modeladmin.excel_data(request, query, model_fields, has_extra_excel_fields) for query in queryset] + + force_csv = (hasattr(settings, 'DJANGO_EXCEL_RESPONSE') and settings.DJANGO_EXCEL_RESPONSE) or (hasattr(modeladmin, 'force_csv') and modeladmin.force_csv) + + return ExcelResponse(excel_data, output_name=modeladmin.model._meta.verbose_name_plural, force_csv=force_csv) + + advanced_export_excel.short_description = _(u'Advanced Export selected %(verbose_name_plural)s as Excel') + + +class ReadonlyModelAdmin(object): + """ Readonly for Update. """ + def get_readonly_fields(self, request, obj=None): + if not hasattr(self, 'readonly_fields_exclude'): + self.readonly_fields_exclude = () + if obj: # editing an existing object + return tuple(set(self.readonly_fields) | set(f.name for f in self.model._meta.fields) - set(self.readonly_fields_exclude)) + return tuple(set(self.readonly_fields) - set(self.readonly_fields_exclude)) + + +class Readonly2ModelAdmin(object): + """ Readonly for Add/Update. """ + def get_readonly_fields(self, request, obj=None): + if not hasattr(self, 'readonly_fields_exclude'): + self.readonly_fields_exclude = () + return tuple(set(self.readonly_fields) | set(f.name for f in self.model._meta.fields) - set(self.readonly_fields_exclude)) + + +class ReadOnlyModelAdmin(ReadonlyModelAdmin): + """ Disables all editing capabilities. """ + change_form_template = 'admin/readonly_form.html' + + def __init__(self, *args, **kwargs): + super(ReadOnlyModelAdmin, self).__init__(*args, **kwargs) + + def get_actions(self, request): + actions = super(ReadOnlyModelAdmin, self).get_actions(request) + if 'delete_selected' in actions: + del actions['delete_selected'] + return actions + + def has_add_permission(self, request): + return False + + def has_delete_permission(self, request, obj=None): + return False + + def save_model(self, request, obj, form, change): + pass + + def delete_model(self, request, obj): + pass + + def save_related(self, request, form, formsets, change): + pass + + +class ChangeOnlyModelAdmin(object): + """ Disables add/delete capabilities. """ + def get_actions(self, request): + actions = super(ChangeOnlyModelAdmin, self).get_actions(request) + if 'delete_selected' in actions: + del actions['delete_selected'] + return actions + + def has_add_permission(self, request): + return False + + def has_delete_permission(self, request, obj=None): + return False + + def delete_model(self, request, obj): + pass + + +class DeleteonlyModelAdmin(object): + """ Disables add/change capabilities. """ + change_form_template = 'admin/deleteonly_form.html' + + def has_add_permission(self, request): + return False + + +class DeleteOnlyModelAdmin(ReadonlyModelAdmin, DeleteonlyModelAdmin): + """ Disables add/change capabilities, fields readonly. """ + + +class AddOnlyModelAdmin(ReadonlyModelAdmin): + """ Disables delete/change capabilities, fields readonly.. """ + change_form_template = 'admin/addonly_form.html' + + def __init__(self, *args, **kwargs): + super(AddOnlyModelAdmin, self).__init__(*args, **kwargs) + + def get_actions(self, request): + actions = super(AddOnlyModelAdmin, self).get_actions(request) + if 'delete_selected' in actions: + del actions['delete_selected'] + return actions + + def has_delete_permission(self, request, obj=None): + return False + + def delete_model(self, request, obj): + pass + + +class SpecifiedQuantityQuerySetModelAdmin(object): + """ Can Only Exist Specified Quantity QuerySet """ + def save_model(self, request, obj, form, change): + # Change or Add + if change: + obj.save() + # Assign ``specified_quantity_queryset`` as 1 when ``specified_quantity_queryset`` not exists + if not hasattr(self, 'specified_quantity_queryset'): + self.specified_quantity_queryset = 1 + # Assert whether ``specified_quantity_queryset`` is ``int`` or not + assert isinstance(self.specified_quantity_queryset, int) + if self.model.objects.count() >= self.specified_quantity_queryset: + return + obj.save() diff --git a/django-admin.py b/django-admin.py new file mode 100644 index 000000000..b124e35a4 --- /dev/null +++ b/django-admin.py @@ -0,0 +1,9 @@ +#!/Users/bradyfukumoto/.local/share/virtualenvs/Intro-Django-CS13-l7vZlwvX/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from django.core.management import execute_from_command_line +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) + sys.exit(execute_from_command_line()) + diff --git a/djorg/__init__.py b/djorg/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/djorg/settings.py b/djorg/settings.py new file mode 100644 index 000000000..5061c0679 --- /dev/null +++ b/djorg/settings.py @@ -0,0 +1,155 @@ +""" +Django settings for djorg project. + +Generated by 'django-admin startproject' using Django 2.1.4. + +For more information on this file, see +https://docs.djangoproject.com/en/2.1/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/2.1/ref/settings/ +""" + +import os +from decouple import config, Csv +import dj_database_url + +# Build paths inside the project like this: os.path.join(BASE_DIR, ...) +# BASE_DIR was used in original project: +BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! + +SECRET_KEY = config('SECRET_KEY') + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = config('DEBUG', cast=bool) + +ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv()) # currently returns ['localhost,127.0.0.1'] +startup = 0 +while startup < 1: + print(ALLOWED_HOSTS) + startup += 1 + +CORS_ORIGIN_ALLOW_ALL = True + +# Application definition + +INSTALLED_APPS = [ + 'rest_framework', + 'rest_framework.authtoken', + 'notes', + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', +] + +MIDDLEWARE = [ + 'corsheaders.middleware.CorsMiddleware', + 'django.middleware.security.SecurityMiddleware', + 'whitenoise.middleware.WhiteNoiseMiddleware', + '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 = 'djorg.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 = 'djorg.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/2.1/ref/settings/#databases + +DATABASE_URL = config('DATABASE_URL') + +# DATABASES = { +# 'default': { +# 'ENGINE': 'django.db.backends.sqlite3', +# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), +# } +# } +DATABASES = {} + +DATABASES['default'] = dj_database_url.config(default=DATABASE_URL, conn_max_age=600) + + + +# Password validation +# https://docs.djangoproject.com/en/2.1/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/2.1/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/2.1/howto/static-files/ + +STATIC_URL = '/static/' +STATIC_ROOT = os.path.join(BASE_DIR, 'static') + +# rest framework: +from rest_framework.authentication import SessionAuthentication, BasicAuthentication, TokenAuthentication + +REST_FRAMEWORK = { + 'DEFAULT_PERMISSION_CLASSES': [ + 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly', + ], + 'DEFAULT_AUTHENTICATION_CLASSES': ( + 'rest_framework.authentication.BasicAuthentication', + 'rest_framework.authentication.SessionAuthentication', + 'rest_framework.authentication.TokenAuthentication', + ), +} \ No newline at end of file diff --git a/djorg/urls.py b/djorg/urls.py new file mode 100644 index 000000000..89d1036e5 --- /dev/null +++ b/djorg/urls.py @@ -0,0 +1,33 @@ +"""djorg URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/2.1/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, include +from rest_framework import routers +from notes.api import PersonalNoteViewSet +from rest_framework.authtoken import views +from django.urls import re_path + +# Make a default router from the routers package, then register that router: +router = routers.DefaultRouter() +router.register(r'notes', PersonalNoteViewSet) # r means regular expression + +# Define url paths: +urlpatterns = [ + path('admin/', admin.site.urls), + path('api/', include(router.urls)), # ends up creating api/notes route ??? + path('api-token-auth/', views.obtain_auth_token), + re_path(r'^api-token-auth/', views.obtain_auth_token), +] diff --git a/djorg/wsgi.py b/djorg/wsgi.py new file mode 100644 index 000000000..7bb827bb0 --- /dev/null +++ b/djorg/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for djorg 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/2.1/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djorg.settings') + +application = get_wsgi_application() diff --git a/guides/day1.md b/guides/day1.md index cd54d6429..21ac3045d 100644 --- a/guides/day1.md +++ b/guides/day1.md @@ -19,7 +19,7 @@ * Add model to `notes/models.py` * Add `'notes'` to `INSTALLED_APPS` in `djorg/settings.py` * `./manage.py showmigrations` -* `./manage.py makemigrations` +* `./manage.py makemigrations` looks at models and determines if new migrations are needed * `./manage.py showmigrations` * `./manage.py migrate` * `./manage.py shell` diff --git a/key_gen.py b/key_gen.py new file mode 100644 index 000000000..7474583ad --- /dev/null +++ b/key_gen.py @@ -0,0 +1,3 @@ +import random +key = ''.join([random.SystemRandom().choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)]) +print(key) \ No newline at end of file diff --git a/manage.py b/manage.py new file mode 100755 index 000000000..ae1e94bc6 --- /dev/null +++ b/manage.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +import os +import sys + +if __name__ == '__main__': + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djorg.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) diff --git a/notes/__init__.py b/notes/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/notes/admin.py b/notes/admin.py new file mode 100644 index 000000000..10f800aea --- /dev/null +++ b/notes/admin.py @@ -0,0 +1,9 @@ +from django.contrib import admin +from .models import Note, PersonalNote + +class NoteAdmin(admin.ModelAdmin): + readonly_fields=('created_at', 'last_modified') + +# Register your models here +admin.site.register(Note, NoteAdmin) +admin.site.register(PersonalNote) diff --git a/notes/api.py b/notes/api.py new file mode 100644 index 000000000..670551e4f --- /dev/null +++ b/notes/api.py @@ -0,0 +1,32 @@ +# this file uses serializers and viewsets +# to describe which parts of the model we want to expose to the API + +from rest_framework import serializers, viewsets +from .models import Note, PersonalNote + +# Name the serializer class after what it is serializing. +# It will inherit from the specific serializer we are using for this project: +class PersonalNoteSerializer(serializers.HyperlinkedModelSerializer): + # Make an inner class aka Meta to tell the serializer what parts of the model we want to access + class Meta: + model = PersonalNote + fields = ('title', 'content') + + def create(self, validated_data): # override default .create functionality + user = self.context['request'].user + # import pdb; pdb.set_trace() + # user = self.context['request'].user + note = PersonalNote.objects.create(user=user, **validated_data) # uses kwarg + return note + +class PersonalNoteViewSet(viewsets.ModelViewSet): # tells which rows to show + # link to the serializer class: + serializer_class = PersonalNoteSerializer + # specify which records to search for: + queryset = Note.objects.all() # create the variable with an empty dictionary of the correct type + def get_queryset(self): + user = self.request.user + if user.is_anonymous: + return PersonalNote.objects.none() + else: + return PersonalNote.objects.filter(user=user) \ No newline at end of file diff --git a/notes/apps.py b/notes/apps.py new file mode 100644 index 000000000..b6155aca3 --- /dev/null +++ b/notes/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class NotesConfig(AppConfig): + name = 'notes' diff --git a/notes/migrations/0001_initial.py b/notes/migrations/0001_initial.py new file mode 100644 index 000000000..91a04c050 --- /dev/null +++ b/notes/migrations/0001_initial.py @@ -0,0 +1,23 @@ +# Generated by Django 2.1.4 on 2018-12-04 23:55 + +from django.db import migrations, models +import uuid + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Note', + fields=[ + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), + ('title', models.CharField(max_length=200)), + ('content', models.TextField(blank=True)), + ], + ), + ] diff --git a/notes/migrations/0002_auto_20181205_2304.py b/notes/migrations/0002_auto_20181205_2304.py new file mode 100644 index 000000000..03b4bc597 --- /dev/null +++ b/notes/migrations/0002_auto_20181205_2304.py @@ -0,0 +1,25 @@ +# Generated by Django 2.1.4 on 2018-12-05 23:04 + +from django.db import migrations, models +import django.utils.timezone + + +class Migration(migrations.Migration): + + dependencies = [ + ('notes', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='note', + name='created_at', + field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), + preserve_default=False, + ), + migrations.AddField( + model_name='note', + name='last_modified', + field=models.DateTimeField(auto_now=True), + ), + ] diff --git a/notes/migrations/0003_personalnote.py b/notes/migrations/0003_personalnote.py new file mode 100644 index 000000000..3cfe16a45 --- /dev/null +++ b/notes/migrations/0003_personalnote.py @@ -0,0 +1,24 @@ +# Generated by Django 2.1.4 on 2018-12-05 23:33 + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('notes', '0002_auto_20181205_2304'), + ] + + operations = [ + migrations.CreateModel( + name='PersonalNote', + fields=[ + ('note_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='notes.Note')), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + bases=('notes.note',), + ), + ] diff --git a/notes/migrations/__init__.py b/notes/migrations/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/notes/models.py b/notes/models.py new file mode 100644 index 000000000..ca90d874f --- /dev/null +++ b/notes/models.py @@ -0,0 +1,16 @@ +from django.db import models +from uuid import uuid4 +from django.contrib.auth.models import User + +# Create your models here. +class Note(models.Model): # extends the Model class from django.db + + id = models.UUIDField(primary_key=True, default=uuid4, editable=False) + title = models.CharField(max_length=200) + content = models.TextField(blank=True) + created_at = models.DateTimeField(auto_now_add=True) # see day2.md re: arguments here + last_modified = models.DateTimeField(auto_now=True) + +class PersonalNote(Note): # Inherits from Note! + user = models.ForeignKey(User, on_delete=models.CASCADE) + diff --git a/notes/tests.py b/notes/tests.py new file mode 100644 index 000000000..7ce503c2d --- /dev/null +++ b/notes/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/notes/views.py b/notes/views.py new file mode 100644 index 000000000..91ea44a21 --- /dev/null +++ b/notes/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here.