Skip to content

sp_py230 lesson7 activity, django Completed #10

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 8 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
2 changes: 1 addition & 1 deletion blogging/admin.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# blogging/admin.py
from django.contrib import admin
from blogging.models import Post, Category


admin.site.register(Post)
admin.site.register(Category)
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.5 on 2020-09-23 19:38

from django.conf import settings
from django.db import migrations, models
Expand Down
2 changes: 1 addition & 1 deletion 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.5 on 2020-09-28 20:10

from django.db import migrations, models

Expand Down
11 changes: 7 additions & 4 deletions blogging/models.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from django.db import models
from django.db import models # <-- This is already in the file
from django.contrib.auth.models import User

class Post(models.Model):
Expand All @@ -12,13 +12,16 @@ class Post(models.Model):
def __str__(self):
return self.title


class Category(models.Model):
pass
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'
verbose_name_plural = 'Categories'

def __str__(self):
return self.name
1 change: 0 additions & 1 deletion blogging/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ def test_string_representation(self):
actual = str(p1)
self.assertEqual(expected, actual)


class CategoryTestCase(TestCase):

def test_string_representation(self):
Expand Down
7 changes: 6 additions & 1 deletion blogging/urls.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
from django.urls import path
from blogging.views import list_view, detail_view

from blogging.views import stub_view, list_view, detail_view

urlpatterns = [
### path('', stub_view, name="blog_index"),
path('', list_view, name="blog_index"),
### path('posts/<int:post_id>/', stub_view, name="blog_detail"),
path('posts/<int:post_id>/', detail_view, name="blog_detail"),
]


28 changes: 19 additions & 9 deletions blogging/views.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,26 @@
from django.shortcuts import render
from blogging.models import Post, Category
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.template import loader

from blogging.models import Post

def stub_view(request, *args, **kwargs):
body = "Stub View\n\n"
if args:
body += "Args:\n"
body += "\n".join(["\t%s" % a for a in args])
if kwargs:
body += "Kwargs:\n"
body += "\n".join(["\t%s: %s" % i for i in kwargs.items()])
return HttpResponse(body, content_type="text/plain")

def list_view(request):
published = Post.objects.exclude(published_date__exact=None)
posts = published.order_by('-published_date')
template = loader.get_template('blogging/list.html')
context = {'posts': posts}
body = template.render(context)
return HttpResponse(body, content_type="text/html")

def detail_view(request, post_id):
published = Post.objects.exclude(published_date__exact=None)
Expand All @@ -12,11 +29,4 @@ def detail_view(request, post_id):
except Post.DoesNotExist:
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)
return render(request, 'blogging/detail.html', context)
2 changes: 2 additions & 0 deletions goDjangoSrvStart.bat
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

start python manage.py runserver
4 changes: 2 additions & 2 deletions 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 = 'zn5wbhnx97(^r(_l-8hg^s)kw4hr@f6fz=4+l2or423&+zgw7r'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
Expand Down Expand Up @@ -56,7 +56,7 @@
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'mysite/templates')],
'DIRS': [os.path.join(BASE_DIR, 'mysite/templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
Expand Down
4 changes: 2 additions & 2 deletions mysite/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<link type="text/css" rel="stylesheet" href="{% static 'django_blog.css' %}">
</head>
<body>
<div id="header"> {# header begins here #}
<div id="header"> {# header begins here #}
<ul id="control-bar">
{% if user.is_authenticated %}
{% if user.is_staff %}<li><a href="{% url 'admin:index' %}">admin</a></li>{% endif %}
Expand All @@ -15,7 +15,7 @@
<li><a href="{% url 'login' %}">login</a></li>
{% endif %}
</ul>
</div> {# header ends here #}
</div> {# header ends here #}
<div id="container">
<div id="content">
{% block content %}
Expand Down
22 changes: 5 additions & 17 deletions mysite/urls.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,14 @@
"""mysite URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/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
from django.urls import path, include # <-- Make sure you have both of these imports.

from django.contrib.auth.views import LoginView, LogoutView


urlpatterns = [
path('', include('blogging.urls')),
path('polling/', include('polling.urls')),
path('', include('blogging.urls')), # <-- add this
path('polling/', include('polling.urls')), # <-- Add this
path('blogging/', include('blogging.urls')), # <-- Add this
path('admin/', admin.site.urls),
path('login/', LoginView.as_view(template_name='login.html'), name="login"),
path('logout/', LogoutView.as_view(next_page='/'), name="logout"),
Expand Down
1 change: 1 addition & 0 deletions polling/admin.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# blogging/admin.py
from django.contrib import admin
from polling.models import Poll

Expand Down
2 changes: 1 addition & 1 deletion polling/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:24
# Generated by Django 2.1.1 on 2020-09-23 14:25

from django.db import migrations, models

Expand Down
1 change: 1 addition & 0 deletions polling/models.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# blogging/models.py
from django.db import models

class Poll(models.Model):
Expand Down
2 changes: 2 additions & 0 deletions polling/templates/polling/list.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
{# polling/templates/polling/list.html #}

{% extends "base.html" %}
{% block content %}
<h1>Polls</h1>
Expand Down
2 changes: 2 additions & 0 deletions polling/urls.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# polling/urls.py

from django.urls import path
from polling.views import list_view, detail_view

Expand Down
107 changes: 107 additions & 0 deletions readmeSetupSteps.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@

rmvirtualenv djangoenv ;***MMM only if already exists
mkvirtualenv djangoenv
pip install django==2.1.5 ;***MMM DO NOT USE 2.1.1 THROWS EXCEPTIONS

django-admin help
django-admin startproject mysite
cd mysite
python manage.py runserver ; start django
open a browser url = localhost:8000 ; test
python manage.py migrate ; create the database (see section in mysite\settings.py)
dir ; note the db.sqlite3 db is created
winpty python manage.py createsuperuser ; create a superuser to admin the db
user = mike
password = Password1!
python manage.py startapp polling ; create a polling app
dir ; note the polling created app folder
edit mysite\settings
section: INSTALL_APPS
add your polling app to the bottom of the list
'polling', ; ***MMM be sure to include the single quotes
git init

create the overall site web templates
mkdir mysite\templates
edit mysite\templates\base.html ; ref the video for the code
edit mysite\settings.py ; add 'DIRS': [os.path.join(BASE_DIR, 'mysite/templates')],

edit mysite\polling\models.py ; ref the video
python manage.py makemigrations ; migrate the changes to the db
python manage.py migrate
edit mysite\polling\admin.py ; register the poll model
start python manage.py runserver ; # Then visit http://localhost:8000/admin/
mkdir mysite\polling\templates\polling ; we create polling view templates under our polling app
edit mysite\polling\templates\polling\list.html ; create template, ref the video
edit mysite\polling\templates\polling\detail.html ; create template, ref the video
edit mysite\polling\views.py ; add the view for the template, ref the video
edit mysite\urls.py ; define the route to your top level site in urlpatterns, see the video
edit mysite\polling\urls.py ; routes for the polling app
start python manage.py runserver ; # Then visit http://localhost:8000/polling/

python manage.py startapp blogging ; create the blogging app
edit mysite\settings
section: INSTALL_APPS
add your polling app to the bottom of the list
'blogging', ; ***MMM be sure to include the single quotes
python manage.py makemigrations blogging ; migrate the table changes to the db for blogging
python manage.py migrate ; update the db

- using the django shell to test interactively
python manage.py shell
from blogging.models import Post
from django.contrib.auth.models import User
all_users = User.objects.all()
p2 = Post(title="Another post",
text="The second one created",
author=all_users[0]).save()
p3 = Post(title="The third one",
text="With the word 'heffalump'",
author=all_users[0]).save()
p4 = Post(title="Posters are a great decoration",
text="When you are a poor college student",
author=all_users[0]).save()
Post.objects.count()

- the blogging app via admin
edit mysite\blogging\admin.py ; ref the video
python manage.py runserver ; start django

------------------
lesson 7 activity

edit blogging/models.py ; per lesson, ie add Category class
python manage.py makemigrations ; comit to the model using migrations
python manage.py migrate ; comit to the db
edit blogging/admin.py ; add Category
python manage.py runserver
http://localhost:8000/admin ; test categories appears in admin
edit tests.py ; test give a name to the displayed category
python manage.py test blogging ; one test will fail
edit blogging/models.py ; per lesson
retest ; verify categories, and name appears
edit blogging/views.py ; per lesson
edit blogging/url.conf ; per lesson
add this to misite/misite/urls.py ; path('', include('blogging.urls')),
edit blogging/tests.py ; per lesson add test_list_only_published
edit blogging/templates/blogging/list.html ; per lesson, list html
edit blogging/view.html ; per lesson, add list view
edit blogging/templates/blogging/detail.html ; per lesson, detail html
edit blogging/detail.html ; per lesson, add detail view
edit blogging/templates/blogging/list.html ; per lesson, 4 tests run successfully
edit mysite/templates/base.html ; per lesson, static files, css
edit mysite/templates/login.html ; per lesson, for login
edit mysite/mysite/urls.py ; per lesson, for login, logout
http://localhost:8000/admin ; test login page












2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
Django==2.1.1
Django==2.1.5
pytz==2019.3
8 changes: 8 additions & 0 deletions test_results_blogging.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
....
----------------------------------------------------------------------
Ran 4 tests in 0.124s

OK
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
Destroying test database for alias 'default'...