Django实现简易博客
1.首先,我们打开终端创建一个Django项目:django-admin startproject test2.然后创建一个app:python manage.py startapp blog
3.在settings.py里面配置好端口:ALLOWED_HOSTS = ['*']
以及数据库:DATABASES = {
'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'ENGINE':'django.db.backends.mysql', # 数据库的存储引擎
'NAME':'test_django3',
'USER':'xps',
'PASSWORD':'qwe123',
'HOST':'127.0.0.1',
'PORT':'3306',
}
}
4.在项目的_init_.py配置使用mysql:
import pymysql
pymysql.install_as_MySQLdb()5.为blog创建一个urls.py,并用主路由给它分配路由:
from django.urls import path, re_path
from . import views
urlpatterns = [
path('add/',views.add,name='blog_add'),
path('list/',views.list,name='blog_list'),
path('detail/<blog_id>/',views.detail,name='blog_detail'),
path('index/',views.index,name='blog_index'),
path('edit/<blog_id>',views.edit,name='blog_edit'),
path('delete/<blog_id>/',views.delete,name='blog_delete'),
]
6.然后我们在app里面建立model:
from django.db import models
# Create your models here.
# 博客表
class BlogModel(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=100, blank=True)
content = models.TextField()
7.settings.py里面配置模板路径:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS':
,
'APP_DIRS': True, # 设置为True之后,app得注册, 会去app里面的templates找模板
'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',
],
},
},
]
8.建立要用到的模板:
/templates/blog/demo_base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}
{% endblock %}</title>
</head>
<body>
{% block content %}
<div>
<a href="{% url 'blog_index' %}">主页</a>
</div>
{% endblock %}
{% block bodyblock %}
{% endblock %}
</body>
</html>
templates/blog/demo_add.html
{% extends 'blog/demo_base.html' %}
{% block title %}
添加博客
{% endblock %}
{% block bodyblock %}
<h1>添加新文章</h1>
<form action="{% url 'blog_add' %}" method="POST">
{% csrf_token %}
标题<input type="text" autocomplete="off" id="title"
placeholder="请输入标题" name='title'> <br> <br><br>
内容 <textarea name="content" id="content"
placeholder="请输入内容" cols="30" rows="10"></textarea>
<button type="submit">发布博客</button>
</form>
{% endblock %}
t
templates/blog/demo_list.html
{% extends 'blog/demo_base.html' %}
{% block title %}
文章列表
{% endblock %}
{% block bodyblock %}
<h1 style="margin-left: 100px">文章列表</h1>
<table width="400px">
<thead style="font-size:20px">
<tr>
<th>标题</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for blog in blog_list %}
<tr>
<th><a href="{% url 'blog_detail' blog_id=blog.id %}">{{ blog.title }}</a></th>
<th><a href="{% url 'blog_edit' blog_id=blog.id %}">编辑</a> | <a href="{% url 'blog_delete' blog.id %}">删除 </a></th>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
templates/blog/demo_detail.html
{% extends 'blog/demo_base.html' %}
{% block title %}
文章详情
{% endblock %}
{% block bodyblock %}
<h1>{{ blog.title }}</h1>
{{ blog.content }}
{% endblock %}
templates/blog/demo_index.html
{% extends 'blog/demo_base.html' %}
{% block title %}
博客首页
{% endblock %}
{% block bodyblock %}
<tr>
<td><a href="{% url 'blog_add' %}">添加文章</a></td>
<td><a href="{% url 'blog_list' %}">文章列表</a></td>
</tr>
{% endblock %}
/templates/blog/demo_edit.py
{% extends 'blog/demo_base.html' %}
{% block title %}
重新编辑博客
{% endblock %}
{% block bodyblock %}
<h1>重新编辑博客</h1>
<form action="" method="POST">
{% csrf_token %}
标题<input type="text" autocomplete="off" id="title"
placeholder="请输入标题" name='title' value={{ title2 }}>
<br> <br><br>
内容 <textarea name="content" id="content"
placeholder="请输入内容" cols="30" rows="10">{{ content2 }}</textarea>
<button type="submit">发布博客</button>
</form>
{% endblock %}
t
9.接下来就是视图函数的编写
from django.shortcuts import render,redirect,reverse
from django.http import HttpResponse
# 简易博客
from .models import BlogModel
# 博客主页
def index(request):
return render(request, 'blog/demo_index.html')
# 添加博客
def add(request):
if request.method == 'GET':
return render(request,'blog/demo_add.html')
elif request.method == 'POST':
title = request.POST.get('title')
content = request.POST['content']
blog =BlogModel(title=title, content=content)
blog.save()
return redirect(reverse('blog_list'))
else:
return HttpResponse('不能处理的操作')
#博客列表
def list(request):
blog_list = BlogModel.objects.all()
return render(request, 'blog/demo_list.html',
context={'blog_list':blog_list}
)
#文章详情
def detail(request, blog_id):
# 通过id拿到当前的文章
blog = BlogModel.objects.get(id=blog_id)# 返回的是一共对象get有两个就不行了
# blog = BlogModel.objects.filter(id=blog_id)#返回的是QuerySet,在模板里面使用blog.first.title拿到对象的属性
return render(request, 'blog/demo_detail.html',
context={'blog':blog}
)
# 删除文章
def delete(request, blog_id):
blog = BlogModel.objects.get(id=blog_id)
if blog:
blog.delete()
return redirect(reverse('blog_list'))
#编辑文章
def edit(request,blog_id):
if request.method == 'GET':
blog = BlogModel.objects.get(id= blog_id)
return render(request,'blog/demo_edit.html',
context={'title2':blog.title,
'content2':blog.content,
}
)
elif request.method == 'POST':
title = request.POST.get('title')
content = request.POST['content']
blog =BlogModel.objects.filter(id=blog_id)
# print(blog)
# blog =BlogModel.objects.get(id=blog_id)
# blog = BlogModel(title=title,content=content)
# blog.save() # 用get返回来的是一共对象,用属性来修改
blog.update(title=title,content=content) # filter查出来的是QuerySet,有update方法
return redirect(reverse('blog_list'))
else:
return HttpResponse('修改文章出现未知错误!')
10.容易出现问题的几个地方:
(1).url里面的传参与模板里面的参数传递容易混乱,一定要搞清楚!
(2). 编写视图函数的时候,BolgModel.objects.filter与BolgModel.objects.get一定要分清,前者返回的是QuerySet类型的,后者返回的是一个对象。
刚起步,有不懂的地方或者要指正的地方还请大神要指出来。
感谢分享
页:
[1]