Preview
This commit is contained in:
@@ -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/
|
||||
@@ -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/).
|
||||
|
||||
[](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
|
||||
@@ -0,0 +1,4 @@
|
||||
from django.contrib import admin
|
||||
from .models import Post
|
||||
|
||||
admin.site.register(Post)
|
||||
@@ -0,0 +1,5 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class BlogConfig(AppConfig):
|
||||
name = 'blog'
|
||||
@@ -0,0 +1,9 @@
|
||||
from django import forms
|
||||
from .models import Post
|
||||
|
||||
|
||||
class PostForm(forms.ModelForm):
|
||||
|
||||
class Meta:
|
||||
model = Post
|
||||
fields = ('title', 'text',)
|
||||
@@ -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)),
|
||||
],
|
||||
),
|
||||
]
|
||||
@@ -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
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
{% load static %}
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>Django Girls blog - Build %%%BUILDTAG%%%</title>
|
||||
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
|
||||
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
|
||||
<link href='//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
|
||||
<link rel="stylesheet" href="{% static 'css/blog.css' %}">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="page-header">
|
||||
<div class="top-menu" style="float:right">
|
||||
{% if user.is_authenticated %}
|
||||
<h3> {{ request.user }} | <a href="/admin/logout?next=/">Log out</a> </h3>
|
||||
{% else %}
|
||||
<h3> <a href="/admin/login/?next=/">Log in</a> </h3>
|
||||
{% endif %}
|
||||
{% if user.is_authenticated %}
|
||||
<a href="{% url 'post_new' %}" class="top-menu"><span class="glyphicon glyphicon-plus"></span></a>
|
||||
{% endif %}
|
||||
</div>
|
||||
<h1><a href="/">Django Girls Blog</a></h1>
|
||||
</div>
|
||||
<div class="content container">
|
||||
<div class="row">
|
||||
<div class="col-md-8">
|
||||
{% block content %}
|
||||
{% endblock %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,19 @@
|
||||
{% extends 'blog/base.html' %}
|
||||
|
||||
{% block content %}
|
||||
<div class="post">
|
||||
{% if post.published_date %}
|
||||
<div class="date">
|
||||
{{ post.published_date }}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if user.is_authenticated %}
|
||||
<a class="btn btn-default" href="{% url 'post_edit' pk=post.pk %}"><span class="glyphicon glyphicon-pencil"></span></a>
|
||||
{% endif %}
|
||||
<h1>{{ post.title }}</h1>
|
||||
<p>{{ post.text|linebreaksbr }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<h4><a href="/">Back</a></h4>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,12 @@
|
||||
{% extends 'blog/base.html' %}
|
||||
|
||||
{% block content %}
|
||||
<h1>New post</h1>
|
||||
<form method="POST" class="post-form">{% csrf_token %}
|
||||
{{ form.as_p }}
|
||||
<button type="submit" class="save btn btn-default">Save</button>
|
||||
</form>
|
||||
<div>
|
||||
<h4><a href="/">Back</a></h4>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,13 @@
|
||||
{% extends 'blog/base.html' %}
|
||||
|
||||
{% block content %}
|
||||
{% for post in posts %}
|
||||
<div class="post">
|
||||
<div class="date">
|
||||
{{ post.published_date }}
|
||||
</div>
|
||||
<h1><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h1>
|
||||
<p>{{ post.text|linebreaksbr }}</p>
|
||||
</div>
|
||||
{% endfor %}
|
||||
{% endblock %}
|
||||
@@ -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.'],
|
||||
})
|
||||
@@ -0,0 +1,9 @@
|
||||
from django.urls import path
|
||||
from . import views
|
||||
|
||||
urlpatterns = [
|
||||
path('', views.post_list, name='post_list'),
|
||||
path('post/<int:pk>/', views.post_detail, name='post_detail'),
|
||||
path('post/new', views.post_new, name='post_new'),
|
||||
path('post/<int:pk>/edit/', views.post_edit, name='post_edit'),
|
||||
]
|
||||
@@ -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})
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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')
|
||||
@@ -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')),
|
||||
]
|
||||
@@ -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()
|
||||
@@ -0,0 +1 @@
|
||||
Django~=3.0.6
|
||||
Reference in New Issue
Block a user