[项目1] bloger - day1
项目代码:https://github.com/venicid/Project1--Bloger
1.准备工作
1.创建project
PS C:\Users\Administrator\Desktop\bloger> django-admin startproject bloger
2 创建app
PS C:\Users\Administrator\Desktop\bloger> python.exe .\manage.py startapp firstapp
3 setting添加app
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'firstapp',
]
4 更新数据库表
PS C:\Users\Administrator\Desktop\bloger> python.exe .\manage.py makemigrations No changes detected
PS C:\Users\Administrator\Desktop\bloger> python.exe .\manage.py migrate
5 运行runserver
PS C:\Users\Administrator\Desktop\bloger> python.exe .\manage.py runserver
6 创建超级管理员
PS C:\Users\Administrator\Desktop\bloger> python.exe .\manage.py createsuperuser
Username (leave blank to use 'administrator'): adminuser
Email address:
Password:
Password (again):
Superuser created successfully.
2.博客主页
1 Model层:
from django.db import models # Create your models here. class Article(models.Model):
"""博客内容字段"""
title = models.CharField(null=True, blank=True, max_length=) #文章标题
content = models.TextField(null=True, blank=True) #文章内容 def __str__(self):
return self.title
admin 注册
from django.contrib import admin
from firstapp.models import Article
# Register your models here. admin.site.register(Article)
合并数据库
PS C:\Users\Administrator\Desktop\bloger> python.exe .\manage.py makemigrations
Migrations for 'firstapp':
0001_initial.py:
- Create model Article
PS C:\Users\Administrator\Desktop\bloger> python.exe .\manage.py migrate
runserver
添加数据
2 View层
1 获取Article表的所有数据 article_list = Article.objects.all()
from django.shortcuts import render,redirect
from firstapp.models import Article # Create your views here. def index(request):
"""主页视图"""
context = {}
article_list = Article.objects.all() # 获取Article表的所有数据
context['article_list'] = article_list
return render(request, 'index.html', context)
3 T层
1 导入静态文件,页面
2 setting设置
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates').replace('\\','/')],
{% load staticfiles %} <link rel="stylesheet" href="{% static 'css/semantic.css' %}" media="screen" title="no title" charset="utf-8">
<link rel="stylesheet" href="{% static 'css/list_custom.css' %}" media="screen" title="no title" charset="utf-8"> <img src="{% static 'images/tenlogo.png' %}" alt="">
3 渲染目标语言
{% for article in article_list %} <div class="column">
<a class="ui fluid card" href="#detail/215">
<div class="image">
<img src="{% static 'images/img1.jpg' %}" alt="" style="height:200px;object-fit: cover;">
</div>
</a> <div class="title header" href="/detail/215">{{ article.title }}</div> <i class="icon grey unhide"></i>
<span style="color:#bbbbbb">10K</span>
<span class="" style="color:rgb(226, 226, 226)">|</span>
<i class="icon grey checkmark"></i>
<span style="color:#bbbbbb"> people got it</span> </div> {% endfor %}
4 配置 url
from django.conf.urls import url
from django.contrib import admin
from firstapp.views import index urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', index, name='index'),
]
5 过滤器
{{ article.content|truncatechars: }} #过滤器:100个字符
3 文章分类
1 M层
1 tag标签
from django.db import models # Create your models here. class Article(models.Model):
"""博客内容字段"""
title = models.CharField(null=True, blank=True, max_length=) #文章标题
content = models.TextField(null=True, blank=True) #文章内容 TAG_CHOICES = (
('cry','悬疑类型'),
('ai','科幻类型'),
('life','生活类型')
)
tag = models.CharField(null=True, blank=True, max_length=, choices=TAG_CHOICES) def __str__(self):
return self.title
2 数据库注册,合并数据
3 admin后台
2 View层
def index(request):
"""主页视图"""
queryset = request.GET.get('tag')
if queryset:
article_list = Article.objects.filter(tag=queryset) #过滤器
else:
article_list = Article.objects.all() # 获取Article表的所有数据 context = {}
context['article_list'] = article_list
return render(request, 'index.html', context)
3 T 层
<a class="item" href="{% url 'index' %}">全部</a>
<a class="active item" href="?tag=cry">悬疑</a>
<div class="ui container nav">
<div class="ui text four item menu ">
<a class="item" href="http://127.0.0.1:8000/index/">全部</a>
<a class="item" href="?tag=ai">AI</a>
<a class="item" href="?tag=linux">Linux</a>
<a class="item" href="?tag=python">Python</a>
</div>
</div>
<div class="ui mini tag label">
{{ article.tag }}
</div>
3.博客详情页
1.Model层:
不变
2 View层
article = Article.objects.get(id=page_num) #取出id为1的这篇文章
from django.shortcuts import render,redirect
from firstapp.models import Article # Create your views here. def index(request):
"""主页视图"""
context = {}
article_list = Article.objects.all() # 获取Article表的所有数据
context['article_list'] = article_list
return render(request, 'index.html', context) def detail(request,page_num):
"""detail视图"""
context = {}
article = Article.objects.get(id=page_num) #取出id为1的这篇文章
context['article'] = article
return render(request, 'detail.html', context)
url
from django.conf.urls import url
from django.contrib import admin
from firstapp.views import index,detail urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', index, name='index'),
url(r'^detail/(?P<page_num>\d+)$', detail, name='detail'),
]
3 T层
{% load staticfiles %} <link rel="stylesheet" href="{% static 'css/semantic.css' %}" media="screen" title="no title" charset="utf-8">
<link rel="stylesheet" href="{% static 'css/detail.css' %}" media="screen" title="no title" charset="utf-8"> <img src="{% static 'images/tenlogo.png' %}" alt="">
渲染模板语言
<h1 class="ui header">{{ article.title }}</h1>
<p>
{{ article.content }}
</p>
4. 实现跳转功能
<a class="item" href="{% url 'index' %}">全部</a>
<a href="{% url 'detail' article.id %}">
<a href="{% url 'detail' article.id %}">
<h2 class="ui header">
{{ article.title }}
</h2>
</a>
<a href="{% url 'detail' article.id %}">
<i class="angle tiny double grey right icon">READMORE</i>
</a>
<title>{{ article.title }}</title>
5.展示这个文章对应的评论
1 M层
belong_to = models.ForeignKey(to=Article, related_name='under_comments', null=True, blank=True)
from django.db import models # Create your models here. class Article(models.Model):
"""博客内容字段"""
title = models.CharField(null=True, blank=True, max_length=) # 文章标题
content = models.TextField(null=True, blank=True) # 文章内容
TAG_CHOICES = (
('ai', 'ai'),
('python', 'python'),
('linux', 'linux'),
)
tag = models.CharField(null=True, blank=True, max_length=, choices=TAG_CHOICES) def __str__(self):
return self.title class Comment(models.Model):
"""评论字段表"""
name = models.CharField(null=True, blank=True, max_length=)
comment = models.TextField(null=True, blank=True)
belong_to = models.ForeignKey(to=Article, related_name='under_comments', null=True, blank=True) def __str__(self):
return self.comment
2 注册
from django.contrib import admin
from firstapp.models import Article,Comment
# Register your models here. admin.site.register(Article)
admin.site.register(Comment)
3 合并数据库
PS C:\Users\Administrator\Desktop\bloger> python.exe .\manage.py makemigrations
No changes detected
PS C:\Users\Administrator\Desktop\bloger> python.exe .\manage.py makemigrations
2 V 层
不变
def detail(request,page_num):
"""加载文章,评论视图"""
context = {}
article = Article.objects.get(id=page_num) #取出id为1的这篇文章
context['article'] = article
return render(request, 'detail.html', context)
url 不变
3 T层
通过Article的字段under_comments查找评论
{% for comment in article.under_comments.all %}
<div class="comment">
<div class="avatar">
<img src="http://semantic-ui.com/images/avatar/small/matt.jpg" alt="" />
</div>
<div class="content">
<a href="#" class="author">{{ comment.name }}</a>
<div class="metadata">
<div class="date">2 days ago</div>
</div>
<p class="text" style="font-family: 'Raleway', sans-serif;">
{{ comment.comment }}
</p>
</div>
</div>
{% endfor %}
6 form表单提交评论
1 M层:不变
2 V层
1 定义Django表单
from django import forms class CommentForm(forms.Form):
"""定义Django自带的form表单"""
name = forms.CharField(max_length=)
comment = forms.CharField(widget=forms.Textarea)
2 get实例化一个表单
post提交表单数据
from django.shortcuts import render,redirect
from firstapp.models import Article,Comment
from django import forms class CommentForm(forms.Form):
"""定义个Django自带的表单类"""
name = forms.CharField(max_length=50)
comment = forms.CharField() def detail(request,page_num):
"""加载文章,评论视图"""
if request.method == 'GET':
form = CommentForm #实例化表单 if request.method == 'POST':
form = CommentForm(request.POST) #提交数据
# print(form) for testing
if form.is_valid(): #判断表单的数据是否通过验证
name = form.cleaned_data['name']
comment = form.cleaned_data['comment']
a = Article.objects.get(id=page_num) #查找出该文章对应的id
c = Comment(name=name, comment=comment, belong_to=a) #写评论
c.save() #保存数据库
return redirect(to='detail',page_num=page_num) #重定向本页 context = {}
article = Article.objects.get(id=page_num) #取出id为1的这篇文章
context['article'] = article
context['form'] = form
return render(request, 'detail.html', context)
url
from django.conf.urls import url
from django.contrib import admin
from firstapp.views import index, detail urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', index, name='index'),
url(r'^detail/(?P<page_num>\d+)$',detail,name='detail'),
]
3 T层
<form class="ui form" action="" method="post"> {{ form.as_p }}
{% csrf_token %}
<button type="submit" class="ui blue button" >Click</button>
</form>
7.Django自带form表单验证
1 form表单单独写成文件
2.各种验证器
from django import forms
from django.core.exceptions import ValidationError def words_validator(comment):
"""验证器函数"""
if len(comment) < :
raise ValidationError('内容长度不足5个字符') def comment_validator(comment):
"""过滤器"""
if '?' in comment:
raise ValidationError('不能包含这个字符') class CommentForm(forms.Form):
"""定义Django自带的form表单"""
name = forms.CharField(max_length=,
error_messages={
'required': '请输入内容',
},
) comment = forms.CharField( # 修改表单样式
widget=forms.Textarea,
error_messages={
'required':'请输入内容',
},
validators=[words_validator,comment_validator]
)
8.定制表单
1 sematic ui 的表单
<form class="ui form" action="" method="post"> <div class="field">
<label> name</label>
<input type="text" name="name" value="">
</div>
<div class="field">
<label>comment</label>
<textarea></textarea>
</div> <button type="submit" class="ui blue button" >Click</button>
</form>
<tr><th><label for="id_name">Name:</label></th><td><ul class="errorlist"><li>请输入内容</li></ul><input id="id_name" maxlength="" name="name" type="text" /></td></tr>
<tr><th><label for="id_comment">Comment:</label></th><td><ul class="errorlist"><li>请输入内容</li></ul><textarea cols="" id="id_comment" name="comment" rows="">
</textarea></td></tr>
2 错误表单
<div class="ui form">
<div class="two fields">
<div class="field error">
<label>First Name</label>
<input placeholder="First Name" type="text">
</div>
<div class="field">
<label>Last Name</label>
<input placeholder="Last Name" type="text">
</div>
</div>
<div class="field error">
<label>Gender</label>
<div class="ui selection dropdown">
<div class="default text">Select</div>
<i class="dropdown icon"></i>
<input type="hidden" name="gender">
<div class="menu">
<div class="item" data-value="male">Male</div>
<div class="item" data-value="female">Female</div>
</div>
</div>
</div>
<div class="inline field error">
<div class="ui checkbox">
<input type="checkbox" tabindex="" class="hidden">
<label>我同意本条款和条件</label>
</div>
</div>
</div>
3.post传到后台的数据
4.定制错误表单
<form class="ui error tiny form" action="" method="post"> {% if form.errors %}
<div class="ui error message">
{{ form.errors }}
</div>
{% for field in form %}
<div class="{{ field.errors|yesno:'error, ' }} field">
{{ field.label }}
{{ field }}
</div>
{% endfor %} {% else %}
{% for field in form %}
<div class="field">
{{ field.label }}
{{ field }}
</div>
{% endfor %}
{% endif %}
{% csrf_token %}
<button type="submit" class="ui blue button" >Click</button>
</form>
7. 分类视图
1 M层
2 V层
1.视图1 加载文章,评论视图
def detail(request,page_num, error_form=None):
"""加载文章,评论视图"""
form = CommentForm # 实例化表单 context = {}
article = Article.objects.get(id=page_num) # 取出id为1的这篇文章
context['article'] = article if error_form is not None:
context['form'] = error_form
else:
context['form'] = form
return render(request, 'detail.html', context)
视图 2 post提交评论
def detail_comment(request,page_num):
"""post提交评论"""
form = CommentForm(request.POST) # 提交数据
print(form)
if form.is_valid(): # 判断表单的数据是否通过验证
name = form.cleaned_data['name']
comment = form.cleaned_data['comment']
a = Article.objects.get(id=page_num) # 查找出该文章对应的id
c = Comment(name=name, comment=comment, belong_to=a) # 写评论
c.save() # 保存数据库
else:
return detail(request, page_num, error_form=form) return redirect(to='detail',page_num=page_num) # 重定向本页
2.对应url
from django.conf.urls import url
from django.contrib import admin
from firstapp.views import index,detail,detail_comment urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', index, name='index'),
url(r'^detail/(?P<page_num>\d+)$',detail,name='detail'),
url(r'^detail/(?P<page_num>\d+)/detail_comment$', detail_comment, name='detail_comment'),
]
3 T层
<form class="ui error tiny form" action="{% url 'detail_comment' article.id %}" method="post">
<form class="ui error tiny form" action="{% url 'detail_comment' article.id %}" method="post"> {% if form.errors %}
<div class="ui error message">
{{ form.errors }}
</div>
{% for field in form %}
<div class="{{ field.errors|yesno:'error, ' }} field">
{{ field.label }}
{{ field }}
</div>
{% endfor %} {% else %}
{% for field in form %}
<div class="field">
{{ field.label }}
{{ field }}
</div>
{% endfor %}
{% endif %}
{% csrf_token %}
<button type="submit" class="ui blue button" >Click</button>
</form>
8.添加最优评论
1 第二种:最优评论,comment模型中查找数据
- Model层:添加最优评论字段,布尔值,默认false
class Comment(models.Model):
"""评论字段表"""
name = models.CharField(null=True, blank=True, max_length=)
comment = models.TextField(null=True, blank=True)
belong_to = models.ForeignKey(to=Article, related_name='under_comments', null=True, blank=True)
best_comment = models.BooleanField(default=False) # 最优评论字段布尔值 def __str__(self):
return self.comment
更新数据库,后台
2 V层
def detail(request,page_num, error_form=None):
"""加载文章,评论视图"""
form = CommentForm # 实例化表单 context = {}
article = Article.objects.get(id=page_num) # 取出id为1的这篇文章
context['article'] = article # 加载最优评论
a_id = Article.objects.get(id=page_num) # 查找id为1的这个文章
best_comment = Comment.objects.filter(best_comment=True, belong_to=a_id) # 返回这个文章的最优评论
if best_comment:
context['best_comment'] = best_comment[] if error_form is not None:
context['form'] = error_form
else:
context['form'] = form
return render(request, 'detail.html', context)
3 T层
<div class="ui comments"> {% if best_comment %}
<div class="ui mini red left ribbon label">
<i class="icon fire">BEST</i>
</div> <div class="best comment">
<div class="avatar">
<img src="http://semantic-ui.com/images/avatar/small/matt.jpg" alt="" />
</div>
<div class="content">
<a href="#" class="author">{{ best_comment.name }}</a>
<div class="metadata">
<div class="date"> days ago</div>
</div>
<p class="text" style="font-family: 'Raleway', sans-serif;">
{{ best_comment.comment }}
</p>
</div>
</div>
{% endif %} <div class="ui divider"></div> {% for comment in article.under_comments.all %}
<div class="comment">
<div class="avatar">
<img src="http://semantic-ui.com/images/avatar/small/matt.jpg" alt="" />
</div>
<div class="content">
<a href="#" class="author">{{ comment.name }}</a>
<div class="metadata">
<div class="date"> days ago</div>
</div>
<p class="text" style="font-family: 'Raleway', sans-serif;">
{{ comment.comment }}
</p>
</div>
</div>
{% endfor %} </div>
[项目1] bloger - day1的更多相关文章
- 团队项目——站立会议 DAY1
团队项目--站立会议 DAY1 团队成员介绍(5人):张靖颜.何玥.钟灵毓秀.赵莹.王梓萱 今日(2016/5/6)为站立会议的第一天,一起对团队项目进行讨论,并对每个人的 ...
- 项目Alpha冲刺Day1
一.会议照片 二.项目进展 1.今日安排 讨论完成项目的详细设计,并完成数据库的设计,学习powerDesigner的使用 2.问题困难 powerDesigner导出sql语句因为问题无法导入,特别 ...
- 项目Beta冲刺Day1
项目进展 李明皇 今天解决的进度 点击首页list相应条目将信息传到详情页 明天安排 优化信息详情页布局 林翔 今天解决的进度 前后端连接成功 明天安排 开始微信前端+数据库写入 孙敏铭 今天解决的进 ...
- Alpha冲刺Day1
项目Alpha冲刺Day1 一.站立式会议 照片: 今日安排: 今天是项目开始的第一天,我们小组一起开会讨论了一下具体每天代码进度的落实情况,做了一下大体的规划.另外准备搭建一下环境和项目部署. 二. ...
- 团队作业第五次—项目冲刺-Day1
Day1 项目相关 作业相关 具体描述 所属班级 2019秋福大软件工程实践Z班 作业要求 团队作业第五次-项目冲刺 作业正文 hunter--冲刺集合 团队名称 hunter小组 作业目标 最终做出 ...
- Django基础,Day1 - 环境安装与pycharm创建django项目
Django是一个高级Python Web框架,支持快速部署,清理和实用的设计.它可以被轻易部署和提供实用的组件,而开发人员只需要专注于写自己的应用程序,而不需要重复造轮子.并且Django是自由和开 ...
- 用Swift重写公司OC项目(Day1)--程序的AppIcon与LaunchImage如何设置
公司之前的APP呢经过了两次重写,都是使用OC由本人独立开发的,不过这些东西我都不好意思说是自己写的,真心的一个字:丑!!! 客观原因来说主要是公司要的特别急,而且注重的是功能而非效果,公司的美工之前 ...
- 团队作业4——第一次项目冲刺(Alpha版本) Day1
1.开站立式会议: 2.Leangoo任务分解图: 3.开会讨论的结果,任务分派 队员 今日进展 明日安排 林燕 调查产品的市场需求,学习微信开发 完善逻辑架构框架 王李焕 结合实际分析系统设计思路, ...
- Django电商项目---完成注册页面和用户登录day1
完成基本的创建项目.用户注册.登录.注销功能 创建Django项目,创建df_user的App 创建静态文件夹static(跟manage.py保持在同一级别下) 复制静态文件(css + image ...
随机推荐
- hibernate课程 初探单表映射3-4 组件属性
本节内容: 1 简介组件属性 2 demo 1 简介组件属性: <component name = "address" class = "Address" ...
- Django的路由层和视图层
一丶Django 的路由层(URLconf) URL配置(URLconf)就像Django 所支撑网站的目录.它的本质是URL与要为该URL调用的视图函数之间的映射表:你就是以这种方式告诉Django ...
- es6-async
含义 ES2017 标准引入了 async 函数,使得异步操作变得更加方便. async 函数是什么?一句话,它就是 Generator 函数的语法糖. 前文有一个 Generator 函数,依次读取 ...
- Java集合框架—List
Collection |--List:元素是有序的,元素可以重复.因为该集合体系有索引. |--ArrayList:底层的数据结构使用的是数组结构.特点:查询速度很快.但是增删稍慢.线程不同步. |- ...
- Git 团队常用命令操作指南
命令如下: git clone -b <branch name> [remote repository address] 主要就是在clone的时候,后面添加branch的信息. 报错: ...
- SQL优化 · 经典案例 · 索引篇
Introduction 在这些年的工作之中,由于SQL问题导致的数据库故障层出不穷,下面将过去六年工作中遇到的SQL问题总结归类,还原问题原貌,给出分析问题思路和解决问题的方法,帮助用户在使用数据库 ...
- GIT教程笔记
GIT的工作流程: 先在工作目录中添加.修改文件 一般是在工作目录建立你的工程文件夹,然后通过命令行进入文件夹后 git init 初始化 将需要进行版本管理的文件放入缓存区 git add 文件 ...
- The 12th Zhejiang Provincial Collegiate Programming Contest - I Earthstone Keeper浙江省赛
题目:http://acm.zju.edu.cn/onlinejudge/showContestProblem.do?problemId=5501 思路:DFS,用了递归就溢出,所以可能得用非递归的. ...
- JavaScript:理解worker事件api
如果你不是很了解Event事件,建议先看我上一篇随文javascript:理解DOM事件.或者直接看下文worker api. hack 首先,我们需要实例一个Worker的对象,浏览器会根据新创建的 ...
- 用TextKit实现表情混排
Textkit是iOS7新推出的类库,其实是在之前推出的CoreText上的封装,有了这个TextKit,以后不用再拿着CoreText来做累活了,根据苹果的说法,他们开发了两年多才完成,而且他们 ...