diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 000000000..ca6a503d4 Binary files /dev/null and b/.DS_Store differ diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000..7b76094de --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "python.pythonPath": "/Users/mac/.local/share/virtualenvs/Intro-Django-NruQ2JbL/bin/python" +} \ No newline at end of file diff --git a/Pipfile b/Pipfile new file mode 100644 index 000000000..212c4e3ee --- /dev/null +++ b/Pipfile @@ -0,0 +1,20 @@ +[[source]] +name = "pypi" +url = "https://pypi.org/simple" +verify_ssl = true + +[dev-packages] + +[packages] +django = "*" +decouple = "*" +python-decouple = "*" +djangorestframework = "*" +django-cors-headers = "*" +gunicorn = "*" +psycopg2-binary = "*" +dj-database-url = "*" +whitenoise = "*" + +[requires] +python_version = "3.7" diff --git a/Procfile b/Procfile new file mode 100644 index 000000000..138bf4365 --- /dev/null +++ b/Procfile @@ -0,0 +1 @@ +web: gunicorn mysite.wsgi --log-file - \ No newline at end of file diff --git a/manage.py b/manage.py new file mode 100755 index 000000000..390c7673f --- /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', 'mysite.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/mysite/__init__.py b/mysite/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/mysite/settings.py b/mysite/settings.py new file mode 100644 index 000000000..e34095852 --- /dev/null +++ b/mysite/settings.py @@ -0,0 +1,152 @@ +""" +Django settings for mysite 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 +import dj_database_url +# Build paths inside the project like this: os.path.join(BASE_DIR, ...) +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 = [ + 'localhost,127.0.0.1', + 'heroku-django-app.herokuapp.com', +] + + +# Application definition + +INSTALLED_APPS = [ + 'notes', + 'rest_framework', + 'rest_framework.authtoken', + 'corsheaders', + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', +] + +CORS_ORIGIN_ALLOW_ALL = True + +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 = 'mysite.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 = 'mysite.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/2.1/ref/settings/#databases + + +# ****** SPRINT ****** +DATABASES = {} + +DATABASES['default'] = dj_database_url.config(default=config('DATABASE_URL'), conn_max_age=600) + + +# DATABASES = { +# 'default': { +# 'ENGINE': 'django.db.backends.sqlite3', +# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), +# } +# } + + +# 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') + +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/mysite/urls.py b/mysite/urls.py new file mode 100644 index 000000000..aedee08e3 --- /dev/null +++ b/mysite/urls.py @@ -0,0 +1,35 @@ +"""mysite 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, re_path + +from rest_framework import routers +from rest_framework.authtoken import views +from notes.api import PersonalNoteViewSet + + +# What does Router mean + # Client to Server, a Route direction +router = routers.DefaultRouter() +router.register('notes', PersonalNoteViewSet) + +urlpatterns = [ + path('admin/', admin.site.urls), + path('api/', include(router.urls)), + re_path(r'^api-token-auth/', views.obtain_auth_token) +] + + diff --git a/mysite/wsgi.py b/mysite/wsgi.py new file mode 100644 index 000000000..77f71eb33 --- /dev/null +++ b/mysite/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for mysite 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', 'mysite.settings') + +application = get_wsgi_application() 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..02224ee98 --- /dev/null +++ b/notes/admin.py @@ -0,0 +1,12 @@ +from django.contrib import admin +from .models import Note, PersonalNote, SecretNote +# . means look in the current directory + +class NoteAdmin(admin.ModelAdmin): + readonly_fields = ('date_created', 'last_editted') + +# Register your models here. + +admin.site.register(Note, NoteAdmin) +admin.site.register(PersonalNote, NoteAdmin) +admin.site.register(SecretNote) \ No newline at end of file diff --git a/notes/api.py b/notes/api.py new file mode 100644 index 000000000..b20ffd53e --- /dev/null +++ b/notes/api.py @@ -0,0 +1,36 @@ +# This file sets control over what fields should be viewable on our API +# +# + +from rest_framework import serializers, viewsets +from .models import PersonalNote, URLS + +class PersonalNoteSerializer(serializers.HyperlinkedModelSerializer): + # Nested class, called Meta. Chooses which parts of the Meta we want to Access + # Is it always called Meta? + # What does Meta mean? - self referential(arts)/denoting change of position + class Meta: + model = PersonalNote + # Chooses Fields of Records + fields = ('title', 'content') + + def create(self, validated_data): + # import pdb; pdb.set_trace() + user = self.context['request'].user + + note = PersonalNote.objects.create(user=user, **validated_data) + return note + +class PersonalNoteViewSet(viewsets.ModelViewSet): + serializer_class = PersonalNoteSerializer + # Chooses which Records to return + queryset = PersonalNote.objects.all() + + def get_queryset(self): + user = self.request.user + + if user.is_anonymous: + return PersonalNote.objects.none() + + else: + return personal.objects.filter(user=user) 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..35db43f11 --- /dev/null +++ b/notes/migrations/0001_initial.py @@ -0,0 +1,23 @@ +# Generated by Django 2.1.4 on 2018-12-04 19:34 + +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_urls.py b/notes/migrations/0002_urls.py new file mode 100644 index 000000000..bdc922412 --- /dev/null +++ b/notes/migrations/0002_urls.py @@ -0,0 +1,21 @@ +# Generated by Django 2.1.4 on 2018-12-04 20:04 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('notes', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='URLS', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('title', models.CharField(max_length=100)), + ('url', models.URLField()), + ], + ), + ] diff --git a/notes/migrations/0003_auto_20181204_2059.py b/notes/migrations/0003_auto_20181204_2059.py new file mode 100644 index 000000000..ffbed7a0a --- /dev/null +++ b/notes/migrations/0003_auto_20181204_2059.py @@ -0,0 +1,25 @@ +# Generated by Django 2.1.4 on 2018-12-04 20:59 + +from django.db import migrations, models +import django.utils.timezone + + +class Migration(migrations.Migration): + + dependencies = [ + ('notes', '0002_urls'), + ] + + operations = [ + migrations.AddField( + model_name='note', + name='date_created', + field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), + preserve_default=False, + ), + migrations.AddField( + model_name='note', + name='last_editted', + field=models.DateTimeField(auto_now=True), + ), + ] diff --git a/notes/migrations/0004_personalnote.py b/notes/migrations/0004_personalnote.py new file mode 100644 index 000000000..8ec5d8812 --- /dev/null +++ b/notes/migrations/0004_personalnote.py @@ -0,0 +1,24 @@ +# Generated by Django 2.1.4 on 2018-12-04 21:38 + +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', '0003_auto_20181204_2059'), + ] + + 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/0005_secretnote.py b/notes/migrations/0005_secretnote.py new file mode 100644 index 000000000..37a926627 --- /dev/null +++ b/notes/migrations/0005_secretnote.py @@ -0,0 +1,22 @@ +# Generated by Django 2.1.4 on 2018-12-04 21:48 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('notes', '0004_personalnote'), + ] + + operations = [ + migrations.CreateModel( + name='SecretNote', + fields=[ + ('personalnote_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='notes.PersonalNote')), + ('very_secretive', models.BooleanField()), + ], + bases=('notes.personalnote',), + ), + ] 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..e4097aa5d --- /dev/null +++ b/notes/models.py @@ -0,0 +1,46 @@ +from django.db import models +from uuid import uuid4 +from django.contrib.auth.models import User + +# Create your models here. +class Note(models.Model): + id = models.UUIDField(primary_key=True, default=uuid4, editable=False) + title = models.CharField(max_length=200) + content = models.TextField(blank=True) + + # Model update + # Now must makemigrations, then migrate + date_created = models.DateTimeField(auto_now_add=True) + last_editted = models.DateTimeField(auto_now=True) + +class URLS(models.Model): + title = models.CharField(max_length=100) + url = models.URLField(max_length=200) + +class PersonalNote(Note): + user = models.ForeignKey(User, on_delete=models.CASCADE) + +class SecretNote(PersonalNote): + very_secretive = models.BooleanField() + + +# In instances where Models need to be updated, +# you must ./manage.py makemigration, then ./manage.py migrate to update the model + +# models.Model +# gives Django functionality +# eg access to fields such as UUIDField,Charfield, TextField, URLField + +# The difference between ./manage.py shell and pipenv shell +# think of scope locality + +# One advantage to using Django, you can create data quick and easily in the ./manage.py shell +# Normally users would delete records manually through the GUI, but we can do it faster by filtering certain ID's in the shell + +""" +for i in range(0, 40): + n = Note(title=f"Title{i}", content="Details") + # save() is inherited from models.Model + # save() is the save button on the GUI + n.save() +""" \ No newline at end of file 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. diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 000000000..5a9e8ca82 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,9 @@ +dj-database-url==0.5.0 +Django==2.1.4 +django-cors-headers==2.4.0 +djangorestframework==3.9.0 +gunicorn==19.9.0 +psycopg2-binary==2.7.6.1 +python-decouple==3.1 +pytz==2018.7 +whitenoise==4.1.2