参考 自强学堂 https://code.ziqiangxuetang.com/django/django-basic.html
风之清扬 https://blog.csdn.net/a18852867035/article/details/65937407
- 用windows的命令提示符进入设定的工程目录
django-admin.py startproject MyBlog
特别是在 windows 上,如果报错,尝试用 django-admin 代替 django-admin.py 试试
- 新建app
python manage.py startapp MyBlogApp
或 django-admin.py startapp MyBlogApp
- 修改 MyBlog/MyBlog/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'MyBlogApp',
]
- 在models.py内建立表内容:(标题,内容,发布时间等)
注意这个Meta类是Django用来描述模型特性的
class BlogPost(models.Model):
title=models.CharField('标题',max_length=50)
content=models.TextField(help_text='博客内容')
pub=models.DateTimeField('发布时间')
class Meta:
verbose_name = "博客"
verbose_name_plural = verbose_name
ordering = ["-pub"]
def __str__(self):
return self.title
- 创建数据库,注意这里默认用sqlite3,db.sqlite3保存在工程目录下
python manage.py makemigrations
python manage.py migrate
- 管理数据库内容,注册到后台,修改 MyBlog/MyBlogApp/admin.py
#coding=utf-8
from django.contrib import admin
from .models import BlogPost
# Register your models here.
class BlogPostAdmin(admin.ModelAdmin):
list_display = ('title','pub')
admin.site.register(BlogPost,BlogPostAdmin)
- 创建管理员:python manage.py createsuperuser
输入用户名,输入密码,创建成功。
输入以下命令:python manage.py runserver运行服务器
然后在浏览器网址127.0.0.1:8000/admin登录:点击添加博客 - views.py里添加html渲染视图
#coding=utf-8
from django.shortcuts import render,render_to_response
from .models import BlogPost
# Create your views here.
def myBlog(request):
blog_list=BlogPost.objects.all()
return render_to_response('BlogTemplate.html',{'blog_list':blog_list})
- urls.py里:
from django.contrib import admin
from django.urls import path
from MyBlogApp import views
urlpatterns = [
path('myBlogs', views.myBlog),
path('admin/', admin.site.urls),
]
- 在MyBlogApp下新建一个templates文件夹
完成模板配置(T)
在MyBlog文件夹里新建文件夹templates,然后在templates里新建BlogTemplate.html。
我们可以定义一个基础的base.html作为所有页面的基类:base.html
注意模板有特殊的标志和格式
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>标题</title>
</head>
<style type="text/css">
body{
color:#efd;
background: #bbbbbb;
padding: 12px 5em;
margin: 7px;
}
h1{
padding: 2em ;
background: #675;
}
h2{
color: #85F2F2;
border-top: 1px dotted #fff;
}
p{
margin: 1em 0;
}
</style>
<body>
<h1>我的博文</h1>
<h3>这是简洁的博文</h3>
{% block content %}
{% endblock %}
</body>
</html>
- 把templates路径加到settings.py里
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'MyBlogApp/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',
],
},
},
]
- 添加BlogTemplate.html
{% extends "base.html" %}
{% block content %}
{% for post in blog_list %}
<h2>{{ post.title }}</h2>
<p>{{ post.pub}}</p>
<p>{{ post.content }}</p>
{% endfor %}
{% endblock %}
-
在http://127.0.0.1:8000/admin中添加一篇新博客,然后在http://127.0.0.1:8000/myBlogs查看页面刷新情况。
-
修改models.py,注意用__str__,不然会后台会显示一些不希望的量
from django.db import models
# Create your models here.
# coding=utf-8
from django.db import models
# Create your models here.
class Category(models.Model):
"""
博客分类
"""
name = models.CharField('类别', max_length=30)
class Meta:
verbose_name = "类别"
verbose_name_plural = verbose_name
def __str__(self):
return self.name
class Tag(models.Model):
name = models.CharField('标签', max_length=16)
class Meta:
verbose_name = "标签"
verbose_name_plural = verbose_name
def __str__(self):
return self.name
class Blog(models.Model):
title = models.CharField('标题', max_length=32)
author = models.CharField('作者', max_length=16)
content = models.TextField('内容')
pub = models.DateField('发布时间', auto_now_add=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='分类') # 多对一(博客--类别)
tag = models.ManyToManyField(Tag, verbose_name='标签') # (多对多)
class Meta:
verbose_name = "博客"
verbose_name_plural = verbose_name
def __str__(self):
return self.title
class Comment(models.Model):
blog = models.ForeignKey(Blog, on_delete=models.CASCADE, verbose_name='博客') # (博客--评论:一对多)
name = models.CharField('称呼', max_length=16)
email = models.EmailField('邮箱')
content = models.CharField('内容', max_length=240)
pub = models.DateField('发布时间', auto_now_add=True)
class Meta:
verbose_name = "评论"
verbose_name_plural = "评论"
def __str__(self):
return self.content
# coding=utf-8
from django.contrib import admin
# Register your models here.
from .models import *
# Register your models here.
class CategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class TagAdmin(admin.ModelAdmin):
list_display = ('name',)
class BlogAdmin(admin.ModelAdmin):
list_display = ('title', 'category', 'content', 'pub')
class CommentAdmin(admin.ModelAdmin):
list_display = ('blog', 'name', 'content', 'pub')
admin.site.register(Category, CategoryAdmin)
admin.site.register(Tag, TagAdmin)
admin.site.register(Blog, BlogAdmin)
admin.site.register(Comment, CommentAdmin)
- 更新数据库
python manage.py makemigrations
python manage.py migrate
- 新建forms.py,这里的error_messages并不参与网页显示
#coding=utf-8
from django import forms
"""
借此完成博客的评论功能
"""
class CommentForm(forms.Form):
name=forms.CharField(label='称呼',max_length=16,error_messages={
'required':'请填写您的称呼',
'max_length':'称呼太长咯'
})
email=forms.EmailField(label='邮箱',error_messages={
'required':'请填写您的邮箱',
'invalid':'邮箱格式不正确'
})
content=forms.CharField(label='内容',error_messages={
'required':'请填写您的评论内容!',
'max_length':'评论内容太长咯'
})
- 修改view.py,注意这里面的comment_set,是小写Comment进行反向查询
#coding=utf-8
from django.shortcuts import render,render_to_response
from .models import *
from .forms import CommentForm
from django.http import Http404
def get_blogs(request):
blogs=Blog.objects.all().order_by('-pub')#获得所有的博客按时间排序
return render_to_response('blog_list.html',{'blogs':blogs})#传递context:blog参数到固定页面。
def get_details(request,blog_id):
#检查异常
try:
blog=Blog.objects.get(id=blog_id)#获取固定的blog_id的对象;
except Blog.DoesNotExist:
raise Http404
if request.method == 'GET':
form = CommentForm()
else:#请求方法为Post
form = CommentForm(request.POST)
if form.is_valid():
cleaned_data=form.cleaned_data
cleaned_data['blog']=blog
Comment.objects.create(**cleaned_data)
ctx={
'blog':blog,
'comments': blog.comment_set.all().order_by('-pub'),
'form': form
}#返回3个参数
return render(request,'blog_details.html',ctx)
- 修改urls.py,注意第二条正则语句,变量输入要和函数输入一致
from django.conf.urls import url
from django.contrib import admin
from MyBlogApp import views
urlpatterns = [
path('blog/', views.get_blogs, name='blog_get_blog'),
path('detail/<int:blog_id>/', views.get_details, name='blog_get_detail'),
path('admin/', admin.site.urls),
]
- 添加模板
blog_list.html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>我的博客</title>
<style type="text/css">
.blog{
padding: 20px 0px;
}
.blog .info span{
padding-right: 10px;
}
.blog .summary{
padding-top: 20px;
}
</style>
</head>
<body>
<div class="header">
<h1 align="center">我的博客</h1>
</div>
{% for blog in blogs %}
<div align="center" class="blog">
<div class="title">
<a href="{% url 'blog_get_detail' blog.id %}"><h2>{{ blog.title }}</h2></a>
</div>
<div class="info">
<span class="category" style="color: #ff9900;">{{ blog.category.name }}</span>
<span class="author" style="color: #4a86e8;">{{ blog.author }}</span>
<span class="pub" style="color: #6aa84e">{{ blog.pub }}</span>
</div>
<div class="summary">
{{ blog.content | truncatechars:100 }}
</div>
</div>
{% endfor %}
</body>
</html>
blog_details.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ blog.title }}</title>
<style type="text/css">
.blog{
padding: 20px 0px;
}
.blog .info span{
padding-right: 10px;
}
.blog .summary{
padding-top: 20px;
}
</style>
</head>
<body>
<div class="header">
<span><a href="{% url 'blog_get_detail' blog.id %}">{{ blog.title }}</a> </span>
</div>
<div class="content">
<div class="blog">
<div class="title">
<a href="#"><h2>{{ blog.title }}</h2></a>
</div>
<div class="info">
<span class="category" style="color:#ff9900 ;">{{ blog.category.name }}</span>
<span class="author" style="color: #4a86e8">{{ blog.author }}</span>
<span class="pub" style="color: #6aa84f">{{ blog.pub }}</span>
</div>
<div class="summary">
{{ blog.content }}
</div>
<div class="comment">
<div class="comment-diaplay" style="padding-top: 20px;">
<h3>评论</h3>
{% for comment in comments %}
<div class="comment-field" style="padding-top: 10px;">
{{ comment.name }}说:{{ comment.content }}
</div>
{% endfor %}
</div>
<div class="comment-post" style="padding-top: 20px ;">
<h3>提交评论</h3>
<form action="{% url 'blog_get_detail' blog.id %}" method="post">
{% csrf_token %}
{% for field in form %}
<div class="input-field" style="padding-top: 10px;">
{{ field.label }}:{{ field }}
</div>
<div class="error" style="color: red;">
{{ field.errors }}
</div>
{% endfor %}
<button type="submit" style="margin-top:10px ">提交</button>
<input type="button" value="返回">
</form>
</div>
</div>
</div>
</div>
</body>
</html>