博客项目
2019-01-16 本文已影响0人
bda1a329d33d
1.基本配置
-
数据库
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'myblog_db1', 'USER': 'root', 'PASSWORD': 'ryy123456', 'HOST': '127.0.0.1', 'PORT': '3306', } }
-
创建数据库(执行迁移文件)
pytohn manage.py makemgirations pytohn manage.py migrate
-
时区
LANGUAGE_CODE = 'zh-hans' TIME_ZONE = 'Asia/Shanghai'
-
静态资源配置
STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'),#静态资源的真实路径 )
-
创建超级用户
python manage.py createsuperuser
2.创建首页路由
-
创建视图函数
def index(request): return render(request, 'index.html', {})
-
配置url
url(r'^$', index, name='index' )
3.实现分页
-
安装包
pip install django-pure-pagination
-
编写views试图函数
pIndex = int(pIndex) if pIndex == None: pIndex = 1 list1 = BlogPosts.objects.all() p = Paginator(list1,4) list2 = p.page(pIndex) p1 = list2.has_previous() ps = list2.number p2 = list2.has_next() if p1: ps1 = ps-1 if p2: ps2 = ps+1 return render(request,'list.html',locals())
-
HTML模板
<nav class="pagination" style="display: block;"> <ul> {% if p1 %} <li class="next-page"><a href="{% url 'blog:list' ps1 %}">上一页</a></li> {% endif %} {% for a in p.page_range %} <li class="active"><a href="{% url 'blog:list' a %}"> {{ a }}</a></li> {% endfor %} {% if p2 %} <li class="next-page"><a href="{% url 'blog:list' ps2 %}">下一页</a></li> {% endif %} <li><span>共 {{ p.num_pages }} 页 </span></li> </ul> </nav>
3.评论
-
编写views试图函数
def comment(request): blog_id = request.POST.get('blog_id') #前端传过来的用户名,邮箱,评论内容 username = request.POST.get('username') email = request.POST.get('email') comment = request.POST.get('comment-textarea') #实例化一个评论模型 c = Comment() #评论里有一个user字段为必填字段 c.user = BlogUser.objects.get(id=1) #评论得内容 c.content = comment #提交博客的id #评论属于哪个博客下的评论 c.post = Comment.objects.get(id=blog_id) c.save() return redirect(reverse('show',args = (blog_id,)))
-
HTML模板
<div class="title" id="comment"> <h3>评论</h3> </div> <div id="respond"> <form id="comment-form" name="comment-form" action="{% url 'blog:comment' %}" method="POST"> {% csrf_token %} <div class="comment"> <input name="username" id="" class="form-control" size="22" placeholder="您的昵称(必填)" maxlength="15" autocomplete="off" tabindex="1" type="text"> <input type="hidden" name="blog_id" value="{{ blog.id }}"> <div class="comment-box"> <textarea placeholder="您的评论或留言(必填)" name="comment-textarea" id="comment-textarea" cols="100%" rows="3" tabindex="3"></textarea> <div class="comment-ctrl"> <div class="comment-prompt" style="display: none;"><i class="fa fa-spin fa-circle-o-notch"></i> <span class="comment-prompt-text">评论正在提交中...请稍后</span> </div> <div class="comment-success" style="display: none;"><i class="fa fa-check"></i> <span class="comment-prompt-text">评论提交成功...</span></div> <button type="submit" name="comment-submit" id="comment-submit" tabindex="4">评论</button> </div> </div> </div> </form> </div>