├── .env.sample ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── django-nextjs-backend-api.code-workspace ├── railway.toml ├── rav.yaml ├── requirements.txt └── src ├── cfehome ├── __init__.py ├── api.py ├── asgi.py ├── settings.py ├── urls.py └── wsgi.py ├── helpers ├── __init__.py └── api_auth.py ├── manage.py └── waitlists ├── __init__.py ├── admin.py ├── api.py ├── apps.py ├── forms.py ├── migrations ├── 0001_initial.py ├── 0002_waitlistentry_updated.py ├── 0003_waitlistentry_user.py ├── 0004_waitlistentry_description.py └── __init__.py ├── models.py ├── schemas.py ├── tests.py └── views.py /.env.sample: -------------------------------------------------------------------------------- 1 | DJANGO_SECRET_KEY="" 2 | DJANGO_DEBUG=1 3 | CORS_ALLOWED_ORIGINS="http://localhost:3000,http://127.0.0.1:3000" 4 | NEW_ENV="ABC" -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 110 | .pdm.toml 111 | .pdm-python 112 | .pdm-build/ 113 | 114 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 115 | __pypackages__/ 116 | 117 | # Celery stuff 118 | celerybeat-schedule 119 | celerybeat.pid 120 | 121 | # SageMath parsed files 122 | *.sage.py 123 | 124 | # Environments 125 | .env 126 | .venv 127 | env/ 128 | venv/ 129 | ENV/ 130 | env.bak/ 131 | venv.bak/ 132 | 133 | # Spyder project settings 134 | .spyderproject 135 | .spyproject 136 | 137 | # Rope project settings 138 | .ropeproject 139 | 140 | # mkdocs documentation 141 | /site 142 | 143 | # mypy 144 | .mypy_cache/ 145 | .dmypy.json 146 | dmypy.json 147 | 148 | # Pyre type checker 149 | .pyre/ 150 | 151 | # pytype static type analyzer 152 | .pytype/ 153 | 154 | # Cython debug symbols 155 | cython_debug/ 156 | 157 | # PyCharm 158 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 159 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 160 | # and can be added to the global gitignore or merged into this file. For a more nuclear 161 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 162 | #.idea/ 163 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Set the python version as a build-time argument 2 | # with Python 3.12 as the default 3 | ARG PYTHON_VERSION=3.12-slim-bullseye 4 | FROM python:${PYTHON_VERSION} 5 | 6 | # Create a virtual environment 7 | RUN python -m venv /opt/venv 8 | 9 | # Set the virtual environment as the current location 10 | ENV PATH=/opt/venv/bin:$PATH 11 | 12 | # Upgrade pip 13 | RUN pip install --upgrade pip 14 | 15 | # Set Python-related environment variables 16 | ENV PYTHONDONTWRITEBYTECODE 1 17 | ENV PYTHONUNBUFFERED 1 18 | 19 | # Install os dependencies for our mini vm 20 | RUN apt-get update && apt-get install -y \ 21 | # for postgres 22 | libpq-dev \ 23 | # for Pillow 24 | libjpeg-dev \ 25 | # for CairoSVG 26 | libcairo2 \ 27 | # other 28 | gcc \ 29 | && rm -rf /var/lib/apt/lists/* 30 | 31 | # Create the mini vm's code directory 32 | RUN mkdir -p /code 33 | 34 | # Set the working directory to that same code directory 35 | WORKDIR /code 36 | 37 | # Copy the requirements file into the container 38 | COPY requirements.txt /tmp/requirements.txt 39 | 40 | # copy the project code into the container's working directory 41 | COPY ./src /code 42 | 43 | # Install the Python project requirements 44 | RUN pip install -r /tmp/requirements.txt 45 | RUN pip install gunicorn 46 | 47 | # database isn't available during build 48 | # run any other commands that do not need the database 49 | # such as: 50 | # RUN python manage.py collectstatic --noinput 51 | 52 | # set the Django default project name 53 | ARG PROJ_NAME="cfehome" 54 | 55 | # create a bash script to run the Django project 56 | # this script will execute at runtime when 57 | # the container starts and the database is available 58 | RUN printf "#!/bin/bash\n" > ./paracord_runner.sh && \ 59 | printf "RUN_PORT=\"\${PORT:-8000}\"\n\n" >> ./paracord_runner.sh && \ 60 | printf "python manage.py migrate --no-input\n" >> ./paracord_runner.sh && \ 61 | printf "gunicorn ${PROJ_NAME}.wsgi:application --bind \"0.0.0.0:\$RUN_PORT\"\n" >> ./paracord_runner.sh 62 | 63 | # make the bash script executable 64 | RUN chmod +x paracord_runner.sh 65 | 66 | # Clean up apt cache to reduce image size 67 | RUN apt-get remove --purge -y \ 68 | && apt-get autoremove -y \ 69 | && apt-get clean \ 70 | && rm -rf /var/lib/apt/lists/* 71 | 72 | # Run the Django project via the runtime script 73 | # when the container starts 74 | CMD ./paracord_runner.sh -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Coding For Entrepreneurs 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Django <> Next.js - Backend API 2 | 3 | The Django Ninja API backend for the Django x Next.js course. 4 | 5 | 6 | ## Getting Started 7 | 8 | Clone, create virtual environment, activate it, install requirements, then run: 9 | 10 | ```bash 11 | git clone https://github.com/codingforentrepreneurs/django-nextjs-backend-api 12 | ``` 13 | 14 | Create virtual environment 15 | ```bash 16 | # if mac/linux/wsl 17 | python3 -m venv venv 18 | 19 | # if windows powershell 20 | c:\Python312\python.exe -m venv 21 | ``` 22 | 23 | Activate virtual environment 24 | ```bash 25 | # if mac/linux/wsl 26 | source venv/bin/activate 27 | 28 | # if windows powershell 29 | .\venv\Scripts\activate 30 | ``` 31 | 32 | Install requirements 33 | ```bash 34 | # If activated, the command line should start with: 35 | # (venv) 36 | pip install pip --upgrade 37 | pip install -r requirements.txt 38 | ``` 39 | 40 | Copy default env 41 | ```bash 42 | cp .env.sample .env 43 | ``` 44 | 45 | Run project 46 | 47 | ```bash 48 | # Using the Rav CLI: https://github.com/jmitchel3/rav 49 | rav run server 50 | 51 | 52 | # or directly with django 53 | cd src 54 | python manage.py runserver 8001 55 | ``` 56 | 57 | 58 | -------------------------------------------------------------------------------- /django-nextjs-backend-api.code-workspace: -------------------------------------------------------------------------------- 1 | { 2 | "folders": [ 3 | { 4 | "path": "." 5 | } 6 | ], 7 | "settings": {} 8 | } -------------------------------------------------------------------------------- /railway.toml: -------------------------------------------------------------------------------- 1 | [build] 2 | builder = "DOCKERFILE" 3 | dockerfilePath = "./Dockerfile" 4 | watchPatterns = [ 5 | "requirements.txt", 6 | "src/**", 7 | "railway.toml", 8 | "Dockerfile", 9 | ] 10 | -------------------------------------------------------------------------------- /rav.yaml: -------------------------------------------------------------------------------- 1 | scripts: 2 | server: 3 | - cd src && python manage.py runserver 8001 4 | makemigrations: 5 | - cd src && python manage.py makemigrations 6 | migrate: 7 | - cd src && python manage.py migrate 8 | shell: 9 | - cd src && python manage.py shell 10 | curl_auth: | 11 | curl -X POST -H "Content-Type: application/json" -d '{"username": "cfe", "password": "learncode"}' http://127.0.0.1:8001/api/token/pair 12 | curl_protect: | 13 | curl -X GET -H "Authorization: Bearer " http://127.0.0.1:8001/api/me 14 | 15 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Django 2 | django-cors-headers 3 | django-ninja 4 | django-ninja-jwt[crypto] 5 | dj-database-url 6 | psycopg[binary] # psycopg 7 | pydantic[email] 8 | python-decouple 9 | rav -------------------------------------------------------------------------------- /src/cfehome/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforentrepreneurs/django-nextjs-backend-api/99fa8d1da908e53731d7d4f45ae23519c060c512/src/cfehome/__init__.py -------------------------------------------------------------------------------- /src/cfehome/api.py: -------------------------------------------------------------------------------- 1 | import helpers 2 | from ninja import NinjaAPI, Schema 3 | 4 | from ninja_extra import NinjaExtraAPI 5 | from ninja_jwt.authentication import JWTAuth 6 | from ninja_jwt.controller import NinjaJWTDefaultController 7 | 8 | api = NinjaExtraAPI() 9 | api.register_controllers(NinjaJWTDefaultController) 10 | api.add_router("/waitlists/", "waitlists.api.router") 11 | 12 | class UserSchema(Schema): 13 | username: str 14 | is_authenticated: bool 15 | # is not requst.user.is_authenticated 16 | email: str = None 17 | 18 | @api.get("/hello") 19 | def hello(request): 20 | # print(request) 21 | return {"message":"Hello World"} 22 | 23 | @api.get("/me", 24 | response=UserSchema, 25 | auth=helpers.api_auth_user_required) 26 | def me(request): 27 | return request.user -------------------------------------------------------------------------------- /src/cfehome/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for cfehome project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cfehome.settings") 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /src/cfehome/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for cfehome project. 3 | 4 | Generated by 'django-admin startproject' using Django 5.0.1. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/5.0/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/5.0/ref/settings/ 11 | """ 12 | import datetime 13 | from pathlib import Path 14 | from decouple import config 15 | 16 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 17 | BASE_DIR = Path(__file__).resolve().parent.parent 18 | 19 | 20 | # Quick-start development settings - unsuitable for production 21 | # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ 22 | 23 | # SECURITY WARNING: keep the secret key used in production secret! 24 | SECRET_KEY = config("DJANGO_SECRET_KEY", cast=str) 25 | 26 | # SECURITY WARNING: don't run with debug turned on in production! 27 | DEBUG = config("DJANGO_DEBUG", cast=bool, default=False) 28 | 29 | ALLOWED_HOSTS = [ 30 | ".railway.app" 31 | ] 32 | if DEBUG: 33 | ALLOWED_HOSTS = ["*"] 34 | 35 | CSRF_TRUSTED_ORIGINS = [ 36 | "http://*.railway.app", 37 | "https://*.railway.app", 38 | ] 39 | 40 | # Application definition 41 | 42 | INSTALLED_APPS = [ 43 | "django.contrib.admin", 44 | "django.contrib.auth", 45 | "django.contrib.contenttypes", 46 | "django.contrib.sessions", 47 | "django.contrib.messages", 48 | "django.contrib.staticfiles", 49 | # third party 50 | "corsheaders", 51 | "ninja_extra", 52 | "ninja_jwt", 53 | # internal 54 | "waitlists", 55 | ] 56 | 57 | MIDDLEWARE = [ 58 | "django.middleware.security.SecurityMiddleware", 59 | "django.contrib.sessions.middleware.SessionMiddleware", 60 | "corsheaders.middleware.CorsMiddleware", 61 | "django.middleware.common.CommonMiddleware", 62 | "django.middleware.csrf.CsrfViewMiddleware", 63 | "django.contrib.auth.middleware.AuthenticationMiddleware", 64 | "django.contrib.messages.middleware.MessageMiddleware", 65 | "django.middleware.clickjacking.XFrameOptionsMiddleware", 66 | ] 67 | 68 | ROOT_URLCONF = "cfehome.urls" 69 | 70 | CORS_URLS_REGEX = r"^/api/.*$" 71 | CORS_ALLOWED_ORIGINS = [] 72 | ENV_CORS_ALLOWED_ORIGINS = config("CORS_ALLOWED_ORIGINS", cast=str, default="") 73 | for origin in ENV_CORS_ALLOWED_ORIGINS.split(","): 74 | CORS_ALLOWED_ORIGINS.append(f"{origin}".strip().lower()) 75 | 76 | 77 | TEMPLATES = [ 78 | { 79 | "BACKEND": "django.template.backends.django.DjangoTemplates", 80 | "DIRS": [], 81 | "APP_DIRS": True, 82 | "OPTIONS": { 83 | "context_processors": [ 84 | "django.template.context_processors.debug", 85 | "django.template.context_processors.request", 86 | "django.contrib.auth.context_processors.auth", 87 | "django.contrib.messages.context_processors.messages", 88 | ], 89 | }, 90 | }, 91 | ] 92 | 93 | WSGI_APPLICATION = "cfehome.wsgi.application" 94 | 95 | 96 | # Database 97 | # https://docs.djangoproject.com/en/5.0/ref/settings/#databases 98 | 99 | DATABASES = { 100 | "default": { 101 | "ENGINE": "django.db.backends.sqlite3", 102 | "NAME": BASE_DIR / "db.sqlite3", 103 | } 104 | } 105 | 106 | DATABASE_URL = config("DATABASE_URL", cast=str, default="") 107 | if DATABASE_URL != "": 108 | import dj_database_url 109 | DATABASES = { 110 | "default": dj_database_url.config( 111 | default=DATABASE_URL, 112 | conn_max_age=300, 113 | conn_health_checks=True 114 | ) 115 | } 116 | 117 | # Password validation 118 | # https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators 119 | 120 | AUTH_PASSWORD_VALIDATORS = [ 121 | { 122 | "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", 123 | }, 124 | { 125 | "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", 126 | }, 127 | { 128 | "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", 129 | }, 130 | { 131 | "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", 132 | }, 133 | ] 134 | 135 | 136 | # Internationalization 137 | # https://docs.djangoproject.com/en/5.0/topics/i18n/ 138 | 139 | LANGUAGE_CODE = "en-us" 140 | 141 | TIME_ZONE = "UTC" 142 | 143 | USE_I18N = True 144 | 145 | USE_TZ = True 146 | 147 | 148 | # Static files (CSS, JavaScript, Images) 149 | # https://docs.djangoproject.com/en/5.0/howto/static-files/ 150 | 151 | STATIC_URL = "static/" 152 | 153 | # Default primary key field type 154 | # https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field 155 | 156 | DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" 157 | 158 | 159 | NINJA_JWT = { 160 | 'ACCESS_TOKEN_LIFETIME': datetime.timedelta(minutes=60), 161 | 'REFRESH_TOKEN_LIFETIME': datetime.timedelta(days=7), 162 | } -------------------------------------------------------------------------------- /src/cfehome/urls.py: -------------------------------------------------------------------------------- 1 | """ 2 | URL configuration for cfehome project. 3 | 4 | The `urlpatterns` list routes URLs to views. For more information please see: 5 | https://docs.djangoproject.com/en/5.0/topics/http/urls/ 6 | Examples: 7 | Function views 8 | 1. Add an import: from my_app import views 9 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 10 | Class-based views 11 | 1. Add an import: from other_app.views import Home 12 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 13 | Including another URLconf 14 | 1. Import the include() function: from django.urls import include, path 15 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 16 | """ 17 | from django.contrib import admin 18 | from django.urls import path 19 | 20 | from .api import api 21 | 22 | urlpatterns = [ 23 | path("admin/", admin.site.urls), 24 | path("api/", api.urls) 25 | ] 26 | -------------------------------------------------------------------------------- /src/cfehome/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for cfehome 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/5.0/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", "cfehome.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /src/helpers/__init__.py: -------------------------------------------------------------------------------- 1 | from .api_auth import ( 2 | api_auth_user_required, 3 | api_auth_user_or_annon 4 | ) 5 | 6 | 7 | __all__ = [ 8 | api_auth_user_required, 9 | api_auth_user_or_annon 10 | ] -------------------------------------------------------------------------------- /src/helpers/api_auth.py: -------------------------------------------------------------------------------- 1 | from ninja_jwt.authentication import JWTAuth 2 | 3 | 4 | def allow_annon(request): 5 | if not request.user.is_authenticated: 6 | return True 7 | 8 | 9 | api_auth_user_required = [JWTAuth()] 10 | api_auth_user_or_annon = [JWTAuth(), allow_annon] -------------------------------------------------------------------------------- /src/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cfehome.settings") 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == "__main__": 22 | main() 23 | -------------------------------------------------------------------------------- /src/waitlists/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforentrepreneurs/django-nextjs-backend-api/99fa8d1da908e53731d7d4f45ae23519c060c512/src/waitlists/__init__.py -------------------------------------------------------------------------------- /src/waitlists/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | from .models import WaitlistEntry 5 | 6 | admin.site.register(WaitlistEntry) -------------------------------------------------------------------------------- /src/waitlists/api.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | import json 3 | from django.shortcuts import get_object_or_404 4 | from ninja import Router 5 | 6 | import helpers 7 | from ninja_jwt.authentication import JWTAuth 8 | 9 | from .forms import WaitlistEntryCreateForm 10 | from .models import WaitlistEntry 11 | from .schemas import ( 12 | WaitlistEntryCreateSchema, 13 | WaitlistEntryListSchema, 14 | WaitlistEntryDetailSchema, 15 | ErrorWaitlistEntryCreateSchema, 16 | WaitlistEntryUpdateSchema 17 | ) 18 | 19 | router = Router() 20 | 21 | 22 | 23 | # /api/waitlists/ 24 | @router.get("", response=List[WaitlistEntryListSchema], auth=helpers.api_auth_user_required) 25 | def list_wailist_entries(request): 26 | qs = WaitlistEntry.objects.filter(user=request.user) 27 | return qs 28 | 29 | # /api/waitlists/ 30 | @router.post("", 31 | response={ 32 | 201: WaitlistEntryDetailSchema, 33 | 400: ErrorWaitlistEntryCreateSchema 34 | }, 35 | auth=helpers.api_auth_user_or_annon 36 | ) 37 | def create_waitlist_entry(request, data:WaitlistEntryCreateSchema): 38 | form = WaitlistEntryCreateForm(data.dict()) 39 | if not form.is_valid(): 40 | # cleaned_data = form.cleaned_data 41 | # obj = WaitlistEntry(**cleaned_data.dict()) 42 | # {'email': [{'message': 'Cannot use gmail', 'code': ''}]} 43 | form_errors = json.loads(form.errors.as_json()) 44 | return 400, form_errors 45 | obj = form.save(commit=False) 46 | if request.user.is_authenticated: 47 | obj.user = request.user 48 | obj.save() 49 | return 201, obj 50 | 51 | 52 | @router.get("{entry_id}/", response=WaitlistEntryDetailSchema, auth=helpers.api_auth_user_required) 53 | def get_wailist_entry(request, entry_id:int): 54 | obj = get_object_or_404( 55 | WaitlistEntry, 56 | id=entry_id, 57 | user=request.user) 58 | return obj 59 | 60 | @router.put("{entry_id}/", response=WaitlistEntryDetailSchema, auth=helpers.api_auth_user_required) 61 | def update_wailist_entry(request, 62 | entry_id:int, 63 | payload:WaitlistEntryUpdateSchema 64 | ): 65 | obj = get_object_or_404( 66 | WaitlistEntry, 67 | id=entry_id, 68 | user=request.user) 69 | payload_dict = payload.dict() 70 | for k,v in payload_dict.items(): 71 | setattr(obj, k, v) 72 | obj.save() 73 | return obj 74 | 75 | # http DELETE 76 | @router.delete("{entry_id}/delete/", response=WaitlistEntryDetailSchema, auth=helpers.api_auth_user_required) 77 | def delete_wailist_entry(request, entry_id:int): 78 | obj = get_object_or_404( 79 | WaitlistEntry, 80 | id=entry_id, 81 | user=request.user) 82 | obj.delete() 83 | return obj -------------------------------------------------------------------------------- /src/waitlists/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class WaitlistsConfig(AppConfig): 5 | default_auto_field = "django.db.models.BigAutoField" 6 | name = "waitlists" 7 | -------------------------------------------------------------------------------- /src/waitlists/forms.py: -------------------------------------------------------------------------------- 1 | from django import forms 2 | from django.utils import timezone 3 | from .models import WaitlistEntry 4 | 5 | class WaitlistEntryCreateForm(forms.ModelForm): 6 | # email = forms.EmailField() 7 | class Meta: 8 | model = WaitlistEntry 9 | fields = ['email'] 10 | 11 | def clean_email(self): 12 | email = self.cleaned_data.get("email") 13 | today = timezone.now().day 14 | qs = WaitlistEntry.objects.filter( 15 | email=email, 16 | timestamp__day=today 17 | ) 18 | if qs.count() >= 5: 19 | raise forms.ValidationError("Cannot enter this email again today.") 20 | # if email.endswith('@gmail.com'): 21 | # raise forms.ValidationError('Cannot use gmail') 22 | return email 23 | 24 | -------------------------------------------------------------------------------- /src/waitlists/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 5.0.6 on 2024-06-26 21:29 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | initial = True 8 | 9 | dependencies = [] 10 | 11 | operations = [ 12 | migrations.CreateModel( 13 | name="WaitlistEntry", 14 | fields=[ 15 | ( 16 | "id", 17 | models.BigAutoField( 18 | auto_created=True, 19 | primary_key=True, 20 | serialize=False, 21 | verbose_name="ID", 22 | ), 23 | ), 24 | ("email", models.EmailField(max_length=254)), 25 | ("timestamp", models.DateTimeField(auto_now_add=True)), 26 | ], 27 | ), 28 | ] 29 | -------------------------------------------------------------------------------- /src/waitlists/migrations/0002_waitlistentry_updated.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 5.0.6 on 2024-06-26 21:50 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | dependencies = [ 8 | ("waitlists", "0001_initial"), 9 | ] 10 | 11 | operations = [ 12 | migrations.AddField( 13 | model_name="waitlistentry", 14 | name="updated", 15 | field=models.DateTimeField(auto_now=True), 16 | ), 17 | ] 18 | -------------------------------------------------------------------------------- /src/waitlists/migrations/0003_waitlistentry_user.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 5.0.6 on 2024-06-28 20:02 2 | 3 | import django.db.models.deletion 4 | from django.conf import settings 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | dependencies = [ 10 | ("waitlists", "0002_waitlistentry_updated"), 11 | migrations.swappable_dependency(settings.AUTH_USER_MODEL), 12 | ] 13 | 14 | operations = [ 15 | migrations.AddField( 16 | model_name="waitlistentry", 17 | name="user", 18 | field=models.ForeignKey( 19 | blank=True, 20 | default=None, 21 | null=True, 22 | on_delete=django.db.models.deletion.SET_NULL, 23 | to=settings.AUTH_USER_MODEL, 24 | ), 25 | ), 26 | ] 27 | -------------------------------------------------------------------------------- /src/waitlists/migrations/0004_waitlistentry_description.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 5.0.6 on 2024-06-30 17:54 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | dependencies = [ 8 | ("waitlists", "0003_waitlistentry_user"), 9 | ] 10 | 11 | operations = [ 12 | migrations.AddField( 13 | model_name="waitlistentry", 14 | name="description", 15 | field=models.TextField(blank=True, null=True), 16 | ), 17 | ] 18 | -------------------------------------------------------------------------------- /src/waitlists/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingforentrepreneurs/django-nextjs-backend-api/99fa8d1da908e53731d7d4f45ae23519c060c512/src/waitlists/migrations/__init__.py -------------------------------------------------------------------------------- /src/waitlists/models.py: -------------------------------------------------------------------------------- 1 | from django.conf import settings 2 | from django.db import models 3 | 4 | User = settings.AUTH_USER_MODEL # "auth.User" 5 | 6 | # Create your models here. 7 | class WaitlistEntry(models.Model): 8 | # user = 9 | user = models.ForeignKey(User, default=None, null=True, blank=True, on_delete=models.SET_NULL) 10 | # user_id ^ 11 | email = models.EmailField() 12 | description = models.TextField(blank=True, null=True) 13 | updated = models.DateTimeField(auto_now=True) 14 | timestamp = models.DateTimeField(auto_now_add=True) -------------------------------------------------------------------------------- /src/waitlists/schemas.py: -------------------------------------------------------------------------------- 1 | from typing import List, Any, Optional 2 | from datetime import datetime 3 | from ninja import Schema 4 | from pydantic import EmailStr 5 | 6 | 7 | class WaitlistEntryCreateSchema(Schema): 8 | # Create -> Data 9 | # WaitlistEntryIn 10 | email: EmailStr 11 | 12 | class ErrorWaitlistEntryCreateSchema(Schema): 13 | # Create -> Data 14 | # WaitlistEntryIn 15 | email: List[Any] 16 | # non_field_errors: List[dict] = [] 17 | 18 | 19 | class WaitlistEntryListSchema(Schema): 20 | # List -> Data 21 | # WaitlistEntryOut 22 | id: int 23 | email: EmailStr 24 | updated: datetime 25 | timestamp: datetime 26 | description: Optional[str] = "" 27 | 28 | 29 | class WaitlistEntryDetailSchema(Schema): 30 | # Get -> Data 31 | # WaitlistEntryOut 32 | id: int 33 | email: EmailStr 34 | updated: datetime 35 | timestamp: datetime 36 | description: Optional[str] = "" 37 | 38 | 39 | class WaitlistEntryUpdateSchema(Schema): 40 | # Put -> Data 41 | # WaitlistEntryOut 42 | # id: int 43 | description: str = "" -------------------------------------------------------------------------------- /src/waitlists/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /src/waitlists/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | 3 | # Create your views here. 4 | --------------------------------------------------------------------------------