Skip to content

Lesson 7: Blog update #11

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added .DS_Store
Binary file not shown.
Binary file added blogging/.DS_Store
Binary file not shown.
14 changes: 12 additions & 2 deletions blogging/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,15 @@
from blogging.models import Post, Category


admin.site.register(Post)
admin.site.register(Category)
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
exclude = ('posts',)


class CategoryInline(admin.TabularInline):
model = Category.posts.through


@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
inlines = [CategoryInline]
76 changes: 38 additions & 38 deletions blogging/fixtures/blogging_test_fixture.json
Original file line number Diff line number Diff line change
@@ -1,38 +1,38 @@
[
{
"pk": 1,
"model": "auth.user",
"fields": {
"username": "admin",
"first_name": "Mr.",
"last_name": "Administrator",
"is_active": true,
"is_superuser": true,
"is_staff": true,
"last_login": "2013-05-24T05:35:58.628Z",
"groups": [],
"user_permissions": [],
"password": "pbkdf2_sha256$10000$1rQazFNdOfFt$6aw/uIrv2uASkZ7moXMTajSN+ySYuowBnbP6ILNQntE=",
"email": "[email protected]",
"date_joined": "2013-05-24T05:35:58.628Z"
}
},
{
"pk": 2,
"model": "auth.user",
"fields": {
"username": "noname",
"first_name": "",
"last_name": "",
"is_active": true,
"is_superuser": true,
"is_staff": true,
"last_login": "2013-05-24T05:35:58.628Z",
"groups": [],
"user_permissions": [],
"password": "pbkdf2_sha256$10000$1rQazFNdOfFt$6aw/uIrv2uASkZ7moXMTajSN+ySYuowBnbP6ILNQntE=",
"email": "[email protected]",
"date_joined": "2013-05-24T05:35:58.628Z"
}
}
]
[
{
"pk": 1,
"model": "auth.user",
"fields": {
"username": "admin",
"first_name": "Mr.",
"last_name": "Administrator",
"is_active": true,
"is_superuser": true,
"is_staff": true,
"last_login": "2013-05-24T05:35:58.628Z",
"groups": [],
"user_permissions": [],
"password": "pbkdf2_sha256$10000$1rQazFNdOfFt$6aw/uIrv2uASkZ7moXMTajSN+ySYuowBnbP6ILNQntE=",
"email": "[email protected]",
"date_joined": "2013-05-24T05:35:58.628Z"
}
},
{
"pk": 2,
"model": "auth.user",
"fields": {
"username": "noname",
"first_name": "",
"last_name": "",
"is_active": true,
"is_superuser": true,
"is_staff": true,
"last_login": "2013-05-24T05:35:58.628Z",
"groups": [],
"user_permissions": [],
"password": "pbkdf2_sha256$10000$1rQazFNdOfFt$6aw/uIrv2uASkZ7moXMTajSN+ySYuowBnbP6ILNQntE=",
"email": "[email protected]",
"date_joined": "2013-05-24T05:35:58.628Z"
}
}
]
2 changes: 1 addition & 1 deletion blogging/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Generated by Django 2.1.1 on 2019-10-29 01:39
# Generated by Django 2.1.1 on 2020-12-19 00:22

from django.conf import settings
from django.db import migrations, models
Expand Down
9 changes: 6 additions & 3 deletions blogging/migrations/0002_category.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Generated by Django 2.1.1 on 2019-11-05 03:35
# Generated by Django 2.1.1 on 2020-12-21 19:42

from django.db import migrations, models

Expand All @@ -13,10 +13,13 @@ class Migration(migrations.Migration):
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('id', models.AutoField(auto_created=True, primary_key=True,
serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=128)),
('description', models.TextField(blank=True)),
('posts', models.ManyToManyField(blank=True, related_name='categories', to='blogging.Post')),
('posts', models.ManyToManyField(blank=True,
related_name='categories',
to='blogging.Post')),
],
),
]
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Generated by Django 2.1.1 on 2019-11-05 03:42
# Generated by Django 2.1.1 on 2020-12-22 02:21

from django.db import migrations

Expand Down
16 changes: 9 additions & 7 deletions blogging/models.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,26 @@
from django.db import models
from django.contrib.auth.models import User


class Post(models.Model):
def __str__(self):
return self.title

title = models.CharField(max_length=128)
text = models.TextField(blank=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
published_date = models.DateTimeField(blank=True, null=True)

def __str__(self):
return self.title

class Category(models.Model):
name = models.CharField(max_length=128)
description = models.TextField(blank=True)
posts = models.ManyToManyField(Post, blank=True, related_name='categories')
def __str__(self):
return self.name

class Meta:
verbose_name_plural = 'Categories'

def __str__(self):
return self.name
name = models.CharField(max_length=128)
description = models.TextField(blank=True)
posts = models.ManyToManyField(Post, blank=True, related_name='categories')
2 changes: 1 addition & 1 deletion blogging/static/django_blog.css
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
body {
background-color: #eee;
color: #111;
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
font-family: 'HelveticaNeue-Light', 'Helvetica Neue Light', 'Helvetica Neue', Helvetica, Arial, 'Lucida Grande', sans-serif;
margin:0;
padding:0;
}
Expand Down
Binary file added blogging/templates/.DS_Store
Binary file not shown.
Binary file added blogging/templates/blogging/.DS_Store
Binary file not shown.
20 changes: 10 additions & 10 deletions blogging/templates/blogging/detail.html
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
{% extends "base.html" %}
{% extends 'base.html' %}

{% block content %}
<a class="backlink" href="/">Home</a>
<a class='backlink' href='/'>Home</a>
<h1>{{ post }}</h1>
<p class="byline">
Posted by {{ post.author.username }} &mdash; {{ post.published_date }}
<p class='byline'>
Posted by {{ post.author.username }} &mdash; {{ post.published_date }}
</p>
<div class="post-body">
{{ post.text }}
<div class='post-body'>
{{ post.text }}
</div>
<ul class="categories">
{% for category in post.categories.all %}
<li>{{ category }}</li>
{% endfor %}
<ul class='categories'>
{% for category in post.categories.all %}
<li>{{ category }}</li>
{% endfor %}
</ul>
{% endblock %}
38 changes: 18 additions & 20 deletions blogging/templates/blogging/list.html
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
{% extends "base.html" %}{% block content %}
<h1>Recent Posts</h1>
{% comment %} here is where the query happens {% endcomment %}
{% for post in posts %}
<div class="post">
<h2>
<a href="{% url 'blog_detail' post.pk %}">{{ post }}</a>
</h2>
<p class="byline">
Posted by {{ post.author.username }} &mdash; {{ post.published_date }}
</p>
<div class="post-body">
{{ post.text }}
{% extends 'base.html' %}{% block content %}
<h1>Recent Posts</h1>
{% comment %} here is where the query happens {% endcomment %}
{% for post in posts %}
<div class='post'>
<h2><a href="{% url 'blog_detail' post.pk %}">{{ post }}</a></h2>
<p class='byline'>
Posted by {{ post.author.username }} &mdash; {{ post.published_date }}
</p>
<div class='post-body'>
{{ post.text }}
</div>
<ul class='categories'>
{% for category in post.categories.all %}
<li>{{ category }}</li>
{% endfor %}
</ul>
</div>
<ul class="categories">
{% for category in post.categories.all %}
<li>{{ category }}</li>
{% endfor %}
</ul>
</div>
{% endfor %}
{% endfor %}
{% endblock %}
26 changes: 11 additions & 15 deletions blogging/tests.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
import datetime

from django.utils.timezone import utc
from django.test import TestCase
from django.contrib.auth.models import User
from django.utils.timezone import utc

from blogging.models import Post
from blogging.models import Category
from blogging.models import Post, Category


class PostTestCase(TestCase):
Expand All @@ -15,7 +12,7 @@ def setUp(self):
self.user = User.objects.get(pk=1)

def test_string_representation(self):
expected = "This is a title"
expected = 'This is a title'
p1 = Post(title=expected)
actual = str(p1)
self.assertEqual(expected, actual)
Expand All @@ -24,26 +21,25 @@ def test_string_representation(self):
class CategoryTestCase(TestCase):

def test_string_representation(self):
expected = "A Category"
expected = 'A Category'
c1 = Category(name=expected)
actual = str(c1)
self.assertEqual(expected, actual)


class FrontEndTestCase(TestCase):
"""test views provided in the front-end"""
"""Test views provided in the front-end"""
fixtures = ['blogging_test_fixture.json', ]

def setUp(self):
self.now = datetime.datetime.utcnow().replace(tzinfo=utc)
self.timedelta = datetime.timedelta(15)
author = User.objects.get(pk=1)
for count in range(1, 11):
post = Post(title="Post %d Title" % count,
text="foo",
post = Post(title='Post %d Title' % count,
text='foo',
author=author)
if count < 6:
# publish the first five posts
if count < 6: # publish the first five posts
pubdate = self.now - self.timedelta * count
post.published_date = pubdate
post.save()
Expand All @@ -52,17 +48,17 @@ def test_list_only_published(self):
resp = self.client.get('/')
# the content of the rendered response is always a bytestring
resp_text = resp.content.decode(resp.charset)
self.assertTrue("Recent Posts" in resp_text)
self.assertTrue('Recent Posts' in resp_text)
for count in range(1, 11):
title = "Post %d Title" % count
title = 'Post %d Title' % count
if count < 6:
self.assertContains(resp, title, count=1)
else:
self.assertNotContains(resp, title)

def test_details_only_published(self):
for count in range(1, 11):
title = "Post %d Title" % count
title = 'Post %d Title' % count
post = Post.objects.get(title=title)
resp = self.client.get('/posts/%d/' % post.pk)
if count < 6:
Expand Down
4 changes: 2 additions & 2 deletions blogging/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
from blogging.views import list_view, detail_view

urlpatterns = [
path('', list_view, name="blog_index"),
path('posts/<int:post_id>/', detail_view, name="blog_detail"),
path('', list_view, name='blog_index'),
path('posts/<int:post_id>/', detail_view, name='blog_detail'),
]
15 changes: 7 additions & 8 deletions blogging/views.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.template import loader

from blogging.models import Post


def list_view(request):
published = Post.objects.exclude(published_date__exact=None)
posts = published.order_by('-published_date')
context = {'posts': posts}
return render(request, 'blogging/list.html', context)


def detail_view(request, post_id):
published = Post.objects.exclude(published_date__exact=None)
try:
Expand All @@ -13,10 +19,3 @@ def detail_view(request, post_id):
raise Http404
context = {'post': post}
return render(request, 'blogging/detail.html', context)


def list_view(request):
published = Post.objects.exclude(published_date__exact=None)
posts = published.order_by('-published_date')
context = {'posts': posts}
return render(request, 'blogging/list.html', context)
6 changes: 3 additions & 3 deletions manage.py
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
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?"
'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)
2 changes: 1 addition & 1 deletion mysite/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'xak=ca*e6hvh8q5hgfz5l9ees)_pxjif0)ui!ikifg4!enjk+7'
SECRET_KEY = 'ijm-qa2dxu0=u4a6d6wge-!3%ndaqoa#)!8%9yogrd*!$c$d@c'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
Expand Down
Loading