commit 4fac3b4c54dc0b3eff94818c11b66a668d4be271 Author: deusops <> Date: Fri Sep 9 17:06:06 2022 +0000 Preview diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..2fa909e --- /dev/null +++ b/LICENSE @@ -0,0 +1,2 @@ +This work is licensed under the Creative Commons Attribution-ShareAlike 4.0 International License. +To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/4.0/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..007e37b --- /dev/null +++ b/README.md @@ -0,0 +1,58 @@ +# Complete Django Girls Tutorial + +This repository contains the code that one would eventually have were they to go through the [Django Girls tutorial](https://tutorial.djangogirls.org/en/). + +[![CircleCI](https://circleci.com/gh/NdagiStanley/django_girls_complete.svg?style=svg)](https://circleci.com/gh/NdagiStanley/django_girls_complete) + +## Differences + +Expressing my authorial rights, some things are a bit different from the tutorial: + +- A `Log in` and `Log out` links on the page header +- A `Back` link within the *blog-detail* and *blog-edit* pages +- A more extensive `.gitignore` file +- A `.editorconfig` file +- An additional python package in the requirements.txt: `pycodestyle` + +- Within `mysite/settings.py`, + + - Use of `Africa/Nairobi` as my *TIME_ZONE* + - Use of `en-us` as my *LANGUAGE_CODE* + - Addition of `0.0.0.0` and `.herokuapp.com` to the *ALLOWED_HOSTS* list + +## Setup + +In a python virtual environment, run: + +- `pip install -r requirements.txt` +- `python manage.py migrate blog` +- `python manage.py createsuperuser` (to create user that you'll use to log in) + +### Run the application + +```bash +python manage.py runserver +``` + +Now, you are good to go. Your blog is ready. + +### Test + +```bash +python manage.py test +``` + +The application will be live at [0.0.0.0:8000](0.0.0.0:8000) + +### Log in/ out + +- Click on `Log in` (you'll be redirected to the Admin page) +- On the admin page, fill in the credentials of the superuser created in [Setup](#setup) +- Click on the *Log in* button (You'll be redirected back to the page) +- Click on `Log out` to log out. + +### Blog entry + +- Log in +- Click on the `+` button, enter the _**title**_ and _**text**_ +- Finally hit the `Save` button diff --git a/blog/__init__.py b/blog/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/blog/admin.py b/blog/admin.py new file mode 100644 index 0000000..47f03fd --- /dev/null +++ b/blog/admin.py @@ -0,0 +1,4 @@ +from django.contrib import admin +from .models import Post + +admin.site.register(Post) diff --git a/blog/apps.py b/blog/apps.py new file mode 100644 index 0000000..7930587 --- /dev/null +++ b/blog/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class BlogConfig(AppConfig): + name = 'blog' diff --git a/blog/forms.py b/blog/forms.py new file mode 100644 index 0000000..c173a29 --- /dev/null +++ b/blog/forms.py @@ -0,0 +1,9 @@ +from django import forms +from .models import Post + + +class PostForm(forms.ModelForm): + + class Meta: + model = Post + fields = ('title', 'text',) diff --git a/blog/migrations/0001_initial.py b/blog/migrations/0001_initial.py new file mode 100644 index 0000000..4ecfae1 --- /dev/null +++ b/blog/migrations/0001_initial.py @@ -0,0 +1,29 @@ +# Generated by Django 2.0.8 on 2018-08-22 09:02 + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion +import django.utils.timezone + + +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=200)), + ('text', models.TextField()), + ('created_date', models.DateTimeField(default=django.utils.timezone.now)), + ('published_date', models.DateTimeField(blank=True, null=True)), + ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + ), + ] diff --git a/blog/migrations/__init__.py b/blog/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/blog/models.py b/blog/models.py new file mode 100644 index 0000000..98aa052 --- /dev/null +++ b/blog/models.py @@ -0,0 +1,22 @@ +from django.db import models +from django.utils import timezone + + +class Post(models.Model): + """ + model Post + """ + author = models.ForeignKey('auth.User', on_delete=models.CASCADE) + title = models.CharField(max_length=200) + text = models.TextField() + created_date = models.DateTimeField( + default=timezone.now) + published_date = models.DateTimeField( + blank=True, null=True) + + def publish(self): + self.published_date = timezone.now() + self.save() + + def __str__(self): + return self.title diff --git a/blog/static/css/blog.css b/blog/static/css/blog.css new file mode 100644 index 0000000..e32a7d3 --- /dev/null +++ b/blog/static/css/blog.css @@ -0,0 +1,46 @@ +.page-header { + background-color: #ff9400; + margin-top: 0; + padding: 20px 20px 20px 40px; +} + +.page-header h1, .page-header h1 a, .page-header h1 a:visited, .page-header h1 a:active { + color: #ffffff; + font-size: 36pt; + text-decoration: none; +} + +.content { + margin-left: 40px; +} + +h1, h2, h3, h4 { + font-family: 'Lobster', cursive; +} + +.date { + color: #828282; +} + +.save { + float: right; +} + +.post-form textarea, .post-form input { + width: 100%; +} + +.top-menu, .top-menu:hover, .top-menu:visited { + color: #ffffff; + float: right; + font-size: 26pt; + margin-right: 20px; +} + +.post { + margin-bottom: 70px; +} + +.post h1 a, .post h1 a:visited { + color: #000000; +} diff --git a/blog/templates/blog/base.html b/blog/templates/blog/base.html new file mode 100644 index 0000000..32cce15 --- /dev/null +++ b/blog/templates/blog/base.html @@ -0,0 +1,36 @@ +{% load static %} + + + + Django Girls blog - Build %%%BUILDTAG%%% + + + + + + + + +
+
+
+ {% block content %} + {% endblock %} +
+
+
+ + + diff --git a/blog/templates/blog/post_detail.html b/blog/templates/blog/post_detail.html new file mode 100644 index 0000000..e87b0a4 --- /dev/null +++ b/blog/templates/blog/post_detail.html @@ -0,0 +1,19 @@ +{% extends 'blog/base.html' %} + +{% block content %} +
+ {% if post.published_date %} +
+ {{ post.published_date }} +
+ {% endif %} + {% if user.is_authenticated %} + + {% endif %} +

{{ post.title }}

+

{{ post.text|linebreaksbr }}

+
+
+

Back

+
+{% endblock %} diff --git a/blog/templates/blog/post_edit.html b/blog/templates/blog/post_edit.html new file mode 100644 index 0000000..1bae3c8 --- /dev/null +++ b/blog/templates/blog/post_edit.html @@ -0,0 +1,12 @@ +{% extends 'blog/base.html' %} + +{% block content %} +

New post

+
{% csrf_token %} + {{ form.as_p }} + +
+
+

Back

+
+{% endblock %} diff --git a/blog/templates/blog/post_list.html b/blog/templates/blog/post_list.html new file mode 100644 index 0000000..33014d1 --- /dev/null +++ b/blog/templates/blog/post_list.html @@ -0,0 +1,13 @@ +{% extends 'blog/base.html' %} + +{% block content %} + {% for post in posts %} +
+
+ {{ post.published_date }} +
+

{{ post.title }}

+

{{ post.text|linebreaksbr }}

+
+ {% endfor %} +{% endblock %} diff --git a/blog/tests.py b/blog/tests.py new file mode 100644 index 0000000..2416a70 --- /dev/null +++ b/blog/tests.py @@ -0,0 +1,41 @@ +from django.contrib.auth.models import User +from django.test import TestCase +from django.utils import timezone + +from .models import Post +from .forms import PostForm + + +class PostTestCase(TestCase): + def setUp(self): + self.user1 = User.objects.create_user(username="admin") + Post.objects.create(author=self.user1, + title="Test", + text="We are testing this", + created_date=timezone.now(), + published_date=timezone.now()) + + def test_post_is_posted(self): + """Posts are created""" + post1 = Post.objects.get(title="Test") + self.assertEqual(post1.text, "We are testing this") + + def test_valid_form_data(self): + form = PostForm({ + 'title': "Just testing", + 'text': "Repeated tests make the app foul-proof", + }) + self.assertTrue(form.is_valid()) + post1 = form.save(commit=False) + post1.author = self.user1 + post1.save() + self.assertEqual(post1.title, "Just testing") + self.assertEqual(post1.text, "Repeated tests make the app foul-proof") + + def test_blank_form_data(self): + form = PostForm({}) + self.assertFalse(form.is_valid()) + self.assertEqual(form.errors, { + 'title': ['This field is required.'], + 'text': ['This field is required.'], + }) diff --git a/blog/urls.py b/blog/urls.py new file mode 100644 index 0000000..057f634 --- /dev/null +++ b/blog/urls.py @@ -0,0 +1,9 @@ +from django.urls import path +from . import views + +urlpatterns = [ + path('', views.post_list, name='post_list'), + path('post//', views.post_detail, name='post_detail'), + path('post/new', views.post_new, name='post_new'), + path('post//edit/', views.post_edit, name='post_edit'), +] diff --git a/blog/views.py b/blog/views.py new file mode 100644 index 0000000..8697173 --- /dev/null +++ b/blog/views.py @@ -0,0 +1,44 @@ +from django.shortcuts import render, get_object_or_404, redirect +from django.utils import timezone +from .models import Post +from .forms import PostForm + + +def post_list(request): + posts = Post.objects.filter(published_date__lte=timezone.now()).order_by( + 'published_date') + return render(request, 'blog/post_list.html', {'posts': posts}) + + +def post_detail(request, pk): + post = get_object_or_404(Post, pk=pk) + return render(request, 'blog/post_detail.html', {'post': post}) + + +def post_new(request): + if request.method == "POST": + form = PostForm(request.POST) + if form.is_valid(): + post = form.save(commit=False) + post.author = request.user + post.published_date = timezone.now() + post.save() + return redirect('post_detail', pk=post.pk) + else: + form = PostForm() + return render(request, 'blog/post_edit.html', {'form': form}) + + +def post_edit(request, pk): + post = get_object_or_404(Post, pk=pk) + if request.method == "POST": + form = PostForm(request.POST, instance=post) + if form.is_valid(): + post = form.save(commit=False) + post.author = request.user + post.published_date = timezone.now() + post.save() + return redirect('post_detail', pk=post.pk) + else: + form = PostForm(instance=post) + return render(request, 'blog/post_edit.html', {'form': form}) diff --git a/init.sh b/init.sh new file mode 100644 index 0000000..289e9cf --- /dev/null +++ b/init.sh @@ -0,0 +1,15 @@ +#! /bin/sh + + +# User credentials +user=admin +email=admin@example.com +password=pass + +file=db/db.sqlite3 +#if [ -z "$file" ]; then +# echo "from django.contrib.auth.models import User; User.objects.create_superuser('$user', '$email', '$password')" | python3 manage.py shell +#fi + +echo "from django.contrib.auth.models import User; User.objects.create_superuser('$user', '$email', '$password')" | python3 manage.py shell +python3 manage.py migrate diff --git a/manage.py b/manage.py new file mode 100644 index 0000000..66ed3a9 --- /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 0000000..e69de29 diff --git a/mysite/settings.py b/mysite/settings.py new file mode 100644 index 0000000..ee91390 --- /dev/null +++ b/mysite/settings.py @@ -0,0 +1,123 @@ +""" +Django settings for mysite project. + +Generated by 'django-admin startproject' using Django 2.0.8. + +For more information on this file, see +https://docs.djangoproject.com/en/2.0/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/2.0/ref/settings/ +""" + +import os + +# 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.0/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'n069kq!wejc&v9mv8v9!bruaxqop$zyov&k#8q)m+s+u#jnh)e' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = ['127.0.0.1', '0.0.0.0', + '.pythonanywhere.com', '.herokuapp.com'] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'blog', +] + +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 = '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.0/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': os.path.join(BASE_DIR, 'db/db.sqlite3'), + } +} + + +# Password validation +# https://docs.djangoproject.com/en/2.0/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.0/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'Africa/Nairobi' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/2.0/howto/static-files/ + +STATIC_URL = '/static/' +STATIC_ROOT = os.path.join(BASE_DIR, 'static') diff --git a/mysite/urls.py b/mysite/urls.py new file mode 100644 index 0000000..79cc454 --- /dev/null +++ b/mysite/urls.py @@ -0,0 +1,22 @@ +"""mysite URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/2.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, include + +urlpatterns = [ + path('admin/', admin.site.urls), + path('', include('blog.urls')), +] diff --git a/mysite/wsgi.py b/mysite/wsgi.py new file mode 100644 index 0000000..ffbfe4f --- /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.0/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/requirements.txt b/requirements.txt new file mode 100644 index 0000000..c6f7074 --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +Django~=3.0.6