INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog', # 新增
]
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class BlogArticles(models.Model):
title = models.CharField(max_length=300)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
from django.contrib import admin
from blog.models import BlogArticles
# Register your models here.
admin.site.register(BlogArticles)
from django.contrib import admin
from blog.models import BlogArticles
class BlogArticlesAdmin(admin.ModelAdmin):
list_display = ("title", "author", "publish")
list_filter = ("publish", "author")
search_fields = ("title", "body")
raw_id_fields = ("author",)
date_hierarchy = "publish"
ordering = ['-publish', 'author']
admin.site.register(BlogArticles, BlogArticlesAdmin)
settings.py
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 3.0.8.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.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/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'hrfho+k-m!9uqdl8&t94d30zl_b875%=i#yvzwdh2_^zvkz)'
# 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 = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(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 = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.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/3.0/topics/i18n/
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('blog/',include('blog.urls')),
path('admin/', admin.site.urls),
]
models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class BlogArticles(models.Model):
title = models.CharField(max_length=300)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
urls.py
from django.urls import path
from blog import views
urlpatterns = [
path('',views.blog_title),
path('/' ,views.blog_article),
]
views.py
from django.shortcuts import render, get_object_or_404
from .models import BlogArticles
def blog_title(request):
blogs = BlogArticles.objects.all()
return render(request, "blog/titles.html", {"blogs": blogs})
def blog_article(request, article_id):
article = get_object_or_404(BlogArticles, id=article_id)
pub = article.publish
return render(request, "blog/content.html", {"article": article, "publish": pub})
base.html
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="https://github.com/necolas/normalize.css/blob/master/normalize.css">
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
{% block content %}
{% endblock %}
</div>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"> </script>
</body>
</html>
titles.html
{% extends "base.html" %}
{% block title %}blog titles{% endblock %}
{% block content %}
<div class="row text-center vertical-middle-sm">
<h1>我的博客</h1>
</div>
<div class="row">
<div class="col-xs-12 col-md-8">
<ul>
{% for blog in blogs %}
<li><a href="{{ blog.id }}">{{ blog.title }}</a></li>
{% endfor %}
</ul>
</div>
<div class="col-xs-6 col-md-4">
<h2>广告</h2>
<p>跟老齐学:www.itdiffer.com</p>
<img width="200px" src=" https://raw.githubusercontent.com/qiwsir/DjangoPracticeProject/master/python-book2.png">
</div>
</div>
{% endblock %}
content.html
{% extends "base.html" %}
{% block title %}blog article{% endblock %}
{% block content %}
<div class="row text-center vertical-middle-sm">
<h1>{{ article.title }}</h1>
</div>
<div class="row">
<div class="col-xs-12 col-md-8">
<p class="text-center"><span>{{ article.author.username }}
</span><span style="margin-left:20px">{{ publish }}</span>
</p>
<div>{{ article.body }}</div>
</div>
<div class="col-xs-6 col-md-4">
<h2>广告</h2>
<p>跟老齐学:www.itdiffer.com</p>
<img width="200px" src="https://raw.githubusercontent.com/qiwsir/DjangoPracticeProject/master/python-book2.png">
</div>
</div>
{% endblock %}
希望博文对大家有所帮助!博主已经将第一章跑通!