第一篇结束

master
barney 2 years ago
commit 2256642abe
  1. 185
      .gitignore
  2. 0
      blog/__init__.py
  3. 21
      blog/admin.py
  4. 6
      blog/apps.py
  5. 26
      blog/migrations/0001_initial.py
  6. 0
      blog/migrations/__init__.py
  7. 17
      blog/models.py
  8. 3
      blog/tests.py
  9. 12
      blog/urls.py
  10. 49
      blog/views.py
  11. 0
      blog/views/__init__.py
  12. 24
      blog/views/blogDetailView.py
  13. 36
      blog/views/blogListView.py
  14. BIN
      db.sqlite3
  15. 0
      demo/__init__.py
  16. 16
      demo/asgi.py
  17. 125
      demo/settings.py
  18. 22
      demo/urls.py
  19. 16
      demo/wsgi.py
  20. 22
      manage.py
  21. 1
      readme.md

185
.gitignore vendored

@ -0,0 +1,185 @@
### Python template
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
.hypothesis/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# IPython Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# dotenv
.env
# virtualenv
venv/
ENV/
# Spyder project settings
.spyderproject
# Rope project settings
.ropeproject
### VirtualEnv template
# Virtualenv
# http://iamzed.com/2009/05/07/a-primer-on-virtualenv/
[Bb]in
[Ii]nclude
[Ll]ib
[Ll]ib64
[Ll]ocal
[Ss]cripts
pyvenv.cfg
.venv
pip-selfcheck.json
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
# idea folder, uncomment if you don't need it
.idea

@ -0,0 +1,21 @@
from django.contrib import admin
from .models import Blog
# Register your models here.
class BlogAdmin(admin.ModelAdmin):
list_display = ['title','author','content','author_name']
# author字段是关系表,必须用两条下划线指定对应属性
search_fields = ['title','content','author__username']
# readonly_fields = ['author']
# # 保存模型时执行的操作
# def save_model(self, request, obj, form, change):
# if not change:
# # 只有创建时指定作者
# obj.author = request.user
# super(BlogAdmin, self).save_model(request,obj,form,change)
admin.site.register(Blog,BlogAdmin)

@ -0,0 +1,6 @@
from django.apps import AppConfig
class BlogConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'blog'

@ -0,0 +1,26 @@
# Generated by Django 4.1.1 on 2022-09-16 09:33
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='Blog',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200, verbose_name='标题')),
('content', models.TextField(verbose_name='内容')),
('author', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL, verbose_name='作者')),
],
),
]

@ -0,0 +1,17 @@
from django.db import models
# Create your models here.
class Blog(models.Model):
title = models.CharField('标题',max_length=200)
author = models.ForeignKey('auth.User',on_delete=models.SET_NULL,null=True,
verbose_name='作者')
content = models.TextField('内容')
def __str__(self):
return self.title
def author_name(self):
return '%s' % self.author.username
author_name.short_description = '作者名称'

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

@ -0,0 +1,12 @@
from django.urls import path
import blog.views as blog_views
from blog.views.blogListView import BlogListView
from blog.views.blogDetailView import BlogDetailView
urlpatterns = [
# path('list/', blog_views.blog_list, name='list'),
# path('detail/<int:blog_id>/', blog_views.blog_detail, name='detail')
path('list/', BlogListView.as_view(), ),
path('detail/<int:pk>/', BlogDetailView.as_view())
]

@ -0,0 +1,49 @@
from django.http import JsonResponse,HttpResponse
from blog.models import Blog
from django.core.paginator import Paginator # 引入分页功能
'''
url中传入两个参数: page(页号)和page_size(每页最多记录数)
参数错误时使用默认值
'''
def blog_list(request):
# 默认第1页
page = request.GET.get('page', 1)
# 每页默认为20条
page_size = request.GET.get('page_size', 20)
# 所有blog记录
blog_qs = Blog.objects.all()
# 根据页号和每页最多记录数提取对应记录
paginator = Paginator(blog_qs, page_size)
current_page = paginator.get_page(page)
blogs = current_page.object_list
resp = {
'blog_list': [
{
'id': blog.id,
'title': blog.title,
} for blog in blogs
]
}
return HttpResponse(resp.values())
def blog_detail(request,blog_id):
blog = Blog.objects.get(id=blog_id)
resp = {
'blog': [
{
'id': blog.id,
'title': blog.title,
'content': blog.content,
'author': {
'id': blog.author.id,
'username': blog.author.username,
}
}
]
}
return HttpResponse(resp.values())

@ -0,0 +1,24 @@
from django.views.generic.detail import BaseDetailView
from django.http import HttpResponse
from blog.models import Blog
class BlogDetailView(BaseDetailView):
model = Blog
def render_to_response(self,context):
blog = context['object']
data = {
'blog': {
'id': blog.id,
'title': blog.title,
'content': blog.content,
'author': {
'id': blog.author.id,
'username': blog.author.username,
}
}
}
return HttpResponse(data.values())

@ -0,0 +1,36 @@
from django.views.generic.list import BaseListView
from blog.models import Blog
from django.http import HttpResponse
class BlogListView(BaseListView):
model = Blog
# 每页条数
paginate_by = 20
def get_paginate_by(self, queryset):
return self.request.GET.get('page_size') or self.paginate_by
def render_to_response(self, context):
paginator = context['paginator']
current_page = context['page_obj']
blogs = current_page.object_list
data = {
'blog_list': [
{
'id': blog.id,
'title': blog.title,
} for blog in blogs
],
'paginator': {
'total_count': paginator.count,
'num_pages': paginator.num_pages,
'page_size': paginator.per_page,
'page_number': current_page.number,
}
}
return HttpResponse(data.values())

Binary file not shown.

@ -0,0 +1,16 @@
"""
ASGI config for demo 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/4.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'demo.settings')
application = get_asgi_application()

@ -0,0 +1,125 @@
"""
Django settings for demo project.
Generated by 'django-admin startproject' using Django 4.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.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/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-=j-v#l)5rd-ifjvnq_=*dek8_807*@cffo8_1+9w*4+ndw#+b)'
# 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',
'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 = 'demo.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates']
,
'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 = 'demo.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.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/4.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

@ -0,0 +1,22 @@
"""demo URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.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
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls'))
]

@ -0,0 +1,16 @@
"""
WSGI config for demo 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/4.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'demo.settings')
application = get_wsgi_application()

@ -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', 'demo.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()

@ -0,0 +1 @@
#### Django开发从入门到实践-段艺等编著
Loading…
Cancel
Save