[项目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 ...
随机推荐
- iOS 收藏的笔记
目录 UI 资料类 网络篇 图表 动画 菜单栏 数据存储和数据库 第三方库 社交分享 刷新 视频音频 其他 阅读 JS 导航 系统 支付 书籍 工具类 完整项目收集 DEMO UI http://ww ...
- 工作中遇到的有关echarts地图和百度地图的问题
工作中遇到的有关echarts地图和百度地图的问题 *** 前言:在做项目中需要制作一个场景是左边是柱状图,右边是地图,地图上悬浮一个按钮可以切换echarts地图和百度地图.*** 功能: 在点击左 ...
- JS案例练习 — 给div添加样式选择功能
附加效果图: CSS内容: <style> ; padding:0px} li{list-style:none} body{font:24px 'Microsoft YaHei'; col ...
- python 实例方法,类方法,静态方法
实例方法 class Human(object): def __init__(self, weight): self.weight = weight def get_weight(self): ret ...
- xp_delete_files不起作用解决方法
xp_delete_file用来删除数据库的备份文件和维护计划文本报告.示例: ,N'D:\Backup\Diff',N'bak',N'2019-05-29T10:03:41' 第一个参数表示文件类型 ...
- IOS -刷帧动画(CADisplayLink)
@property (nonatomic, assign) int imageY; @end @implementation NJView -(void)awakeFromNib { NSLog(@& ...
- IOS 获取手机的屏幕宽度
//屏幕的宽度 CGFloat screenW=[UIScreen mainScreen].bounds.size.width;
- Unix系统中常用的信号含义
http://blog.csdn.net/u012349696/article/details/50687462 编号为1 ~ 31的信号为传统UNIX支持的信号,是不可靠信号(非实时的),编号为32 ...
- C#条件运算符(?:)
一.C#条件运算符(?:) 条件运算符(?:),有时也称为三元操作符“?:”.它是根据布尔型表达式的值返回?后面的两个值中的一个.如果条件为True,则计算第一个表达式并以它的计算结果为准:如果条件为 ...
- React后台管理系统- rc-pagination分页组件封装
1.用户列表页面使用的rc-pagination分页组件 Github地址: https://github.com/react-component/pagination 2.安装 cnpm insta ...