diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..68265c6 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,26 @@ +{ + "workbench.colorCustomizations": { + "activityBar.activeBackground": "#d0faba", + "activityBar.background": "#d0faba", + "activityBar.foreground": "#15202b", + "activityBar.inactiveForeground": "#15202b99", + "activityBarBadge.background": "#6a9af4", + "activityBarBadge.foreground": "#15202b", + "commandCenter.border": "#15202b99", + "sash.hoverBorder": "#d0faba", + "statusBar.background": "#aff78a", + "statusBar.foreground": "#15202b", + "statusBarItem.hoverBackground": "#8ef45a", + "statusBarItem.remoteBackground": "#aff78a", + "statusBarItem.remoteForeground": "#15202b", + "titleBar.activeBackground": "#aff78a", + "titleBar.activeForeground": "#15202b", + "titleBar.inactiveBackground": "#aff78a99", + "titleBar.inactiveForeground": "#15202b99" + }, + "peacock.color": "#aff78a", + "[python]": { + "editor.defaultFormatter": "ms-python.autopep8" + }, + "python.formatting.provider": "none" +} diff --git a/Pipfile b/Pipfile new file mode 100644 index 0000000..c0bef55 --- /dev/null +++ b/Pipfile @@ -0,0 +1,13 @@ +[[source]] +url = "https://pypi.org/simple" +verify_ssl = true +name = "pypi" + +[packages] +django = "~=3.1.0" +djangorestframework = "~=3.11.0" + +[dev-packages] + +[requires] +python_version = "3.9" diff --git a/Pipfile.lock b/Pipfile.lock new file mode 100644 index 0000000..365eeee --- /dev/null +++ b/Pipfile.lock @@ -0,0 +1,70 @@ +{ + "_meta": { + "hash": { + "sha256": "a3efaebe952258cbe8ae58327da9b004f46b0af8802d3a0044ddab203b76f989" + }, + "pipfile-spec": 6, + "requires": { + "python_version": "3.9" + }, + "sources": [ + { + "name": "pypi", + "url": "https://pypi.org/simple", + "verify_ssl": true + } + ] + }, + "default": { + "asgiref": { + "hashes": [ + "sha256:89b2ef2247e3b562a16eef663bc0e2e703ec6468e2fa8a5cd61cd449786d4f6e", + "sha256:9e0ce3aa93a819ba5b45120216b23878cf6e8525eb3848653452b4192b92afed" + ], + "markers": "python_version >= '3.7'", + "version": "==3.7.2" + }, + "django": { + "hashes": [ + "sha256:0fabc786489af16ad87a8c170ba9d42bfd23f7b699bd5ef05675864e8d012859", + "sha256:72a4a5a136a214c39cf016ccdd6b69e2aa08c7479c66d93f3a9b5e4bb9d8a347" + ], + "index": "pypi", + "markers": "python_version >= '3.6'", + "version": "==3.1.14" + }, + "djangorestframework": { + "hashes": [ + "sha256:5cc724dc4b076463497837269107e1995b1fbc917468d1b92d188fd1af9ea789", + "sha256:a5967b68a04e0d97d10f4df228e30f5a2d82ba63b9d03e1759f84993b7bf1b53" + ], + "index": "pypi", + "markers": "python_version >= '3.5'", + "version": "==3.11.2" + }, + "pytz": { + "hashes": [ + "sha256:7b4fddbeb94a1eba4b557da24f19fdf9db575192544270a9101d8509f9f43d7b", + "sha256:ce42d816b81b68506614c11e8937d3aa9e41007ceb50bfdcb0749b921bf646c7" + ], + "version": "==2023.3.post1" + }, + "sqlparse": { + "hashes": [ + "sha256:5430a4fe2ac7d0f93e66f1efc6e1338a41884b7ddf2a350cedd20ccc4d9d28f3", + "sha256:d446183e84b8349fa3061f0fe7f06ca94ba65b426946ffebe6e3e8295332420c" + ], + "markers": "python_version >= '3.5'", + "version": "==0.4.4" + }, + "typing-extensions": { + "hashes": [ + "sha256:8f92fc8806f9a6b641eaa5318da32b44d401efaac0f6678c9bc448ba3605faa0", + "sha256:df8e4339e9cb77357558cbdbceca33c303714cf861d1eef15e1070055ae8b7ef" + ], + "markers": "python_version < '3.11'", + "version": "==4.8.0" + } + }, + "develop": {} +} diff --git a/config/__init__.py b/config/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/config/asgi.py b/config/asgi.py new file mode 100644 index 0000000..8a9fda7 --- /dev/null +++ b/config/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for config 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/3.1/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') + +application = get_asgi_application() diff --git a/config/settings.py b/config/settings.py new file mode 100644 index 0000000..d72f39e --- /dev/null +++ b/config/settings.py @@ -0,0 +1,132 @@ +""" +Django settings for config project. + +Generated by 'django-admin startproject' using Django 3.1.14. + +For more information on this file, see +https://docs.djangoproject.com/en/3.1/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/3.1/ref/settings/ +""" + +from pathlib import Path + +# 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/3.1/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = '3arb5q=&fxugxcv7s04*&gx$o86!a5zpychq-vz#yu6la!j%#5' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = [] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + + # 3rd-party apps + 'rest_framework', + # Local + 'posts.apps.PostsConfig', +] + + +REST_FRAMEWORK = { + 'DEFAULT_PERMISSION_CLASSES': [ + 'rest_framework.permissions.IsAuthenticated', +] +} + +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 = 'config.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 = 'config.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/3.1/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/3.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/3.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/3.1/howto/static-files/ + +STATIC_URL = '/static/' diff --git a/config/urls.py b/config/urls.py new file mode 100644 index 0000000..008de03 --- /dev/null +++ b/config/urls.py @@ -0,0 +1,8 @@ +from django.contrib import admin +from django.urls import path, include + +urlpatterns = [ + path('admin/', admin.site.urls), + path('api/v1/', include('posts.urls')), + path('api-auth/', include('rest_framework.urls')), +] diff --git a/config/wsgi.py b/config/wsgi.py new file mode 100644 index 0000000..94fcaf1 --- /dev/null +++ b/config/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for config 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/3.1/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') + +application = get_wsgi_application() diff --git a/db.sqlite3 b/db.sqlite3 new file mode 100644 index 0000000..9913097 Binary files /dev/null and b/db.sqlite3 differ diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..8e7ac79 --- /dev/null +++ b/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + """Run administrative tasks.""" + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.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) + + +if __name__ == '__main__': + main() diff --git a/posts/__init__.py b/posts/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/posts/admin.py b/posts/admin.py new file mode 100644 index 0000000..719b924 --- /dev/null +++ b/posts/admin.py @@ -0,0 +1,7 @@ +from django.contrib import admin + + +# Register your models here. +from .models import Post + +admin.site.register(Post) \ No newline at end of file diff --git a/posts/apps.py b/posts/apps.py new file mode 100644 index 0000000..2c2b982 --- /dev/null +++ b/posts/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class PostsConfig(AppConfig): + name = 'posts' diff --git a/posts/migrations/0001_initial.py b/posts/migrations/0001_initial.py new file mode 100644 index 0000000..a5d5a3e --- /dev/null +++ b/posts/migrations/0001_initial.py @@ -0,0 +1,28 @@ +# Generated by Django 3.1.14 on 2023-09-16 11:56 + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='Post', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('title', models.CharField(max_length=50)), + ('body', models.TextField()), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + ), + ] diff --git a/posts/migrations/__init__.py b/posts/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/posts/models.py b/posts/models.py new file mode 100644 index 0000000..ad90adc --- /dev/null +++ b/posts/models.py @@ -0,0 +1,12 @@ +from django.db import models +from django.contrib.auth.models import User + +class Post(models.Model): + author = models.ForeignKey(User, on_delete=models.CASCADE) + title = models.CharField(max_length=50) + body = models.TextField() + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + + def __str__(self): + return self.title \ No newline at end of file diff --git a/posts/permissions.py b/posts/permissions.py new file mode 100644 index 0000000..9a96802 --- /dev/null +++ b/posts/permissions.py @@ -0,0 +1,10 @@ +from rest_framework import permissions + +class IsAuthorOrReadOnly(permissions.BasePermission): + def has_object_permission(self, request, view, obj): + # Read-only permissions are allowed for any request + if request.method in permissions.SAFE_METHODS: + return True + + # Write permissions are only allowed to the author of a post + return obj.author == request.user \ No newline at end of file diff --git a/posts/serializers.py b/posts/serializers.py new file mode 100644 index 0000000..c792289 --- /dev/null +++ b/posts/serializers.py @@ -0,0 +1,8 @@ +from rest_framework import serializers +from .models import Post + +class PostSerializer(serializers.ModelSerializer): + + class Meta: + fields = ('id', 'author', 'title', 'body', 'created_at',) + model = Post \ No newline at end of file diff --git a/posts/tests.py b/posts/tests.py new file mode 100644 index 0000000..f014943 --- /dev/null +++ b/posts/tests.py @@ -0,0 +1,26 @@ +from django.test import TestCase +from django.contrib.auth.models import User +from .models import Post + +class BlogTests(TestCase): + + @classmethod + def setUpTestData(cls): + # Create a user + testuser1 = User.objects.create_user( + username='testuser1', password='abc123') + testuser1.save() + + # Create a blog post + test_post = Post.objects.create( + author=testuser1, title='Blog title', body='Body content...') + test_post.save() + + def test_blog_content(self): + post = Post.objects.get(id=1) + author = f'{post.author}' + title = f'{post.title}' + body = f'{post.body}' + self.assertEqual(author, 'testuser1') + self.assertEqual(title, 'Blog title') + self.assertEqual(body, 'Body content...') \ No newline at end of file diff --git a/posts/urls.py b/posts/urls.py new file mode 100644 index 0000000..7a36875 --- /dev/null +++ b/posts/urls.py @@ -0,0 +1,7 @@ +from django.urls import path +from .views import PostList, PostDetail + +urlpatterns = [ + path('/', PostDetail.as_view()), + path('', PostList.as_view()), +] \ No newline at end of file diff --git a/posts/views.py b/posts/views.py new file mode 100644 index 0000000..3958be2 --- /dev/null +++ b/posts/views.py @@ -0,0 +1,14 @@ +from rest_framework import generics +from .models import Post +from .permissions import IsAuthorOrReadOnly +from .serializers import PostSerializer + +class PostList(generics.ListCreateAPIView): + queryset = Post.objects.all() + serializer_class = PostSerializer + + +class PostDetail(generics.RetrieveUpdateDestroyAPIView): + permission_classes = (IsAuthorOrReadOnly,) + queryset = Post.objects.all() + serializer_class = PostSerializer \ No newline at end of file