Python学习day14 BBS功能和聊天室

Created on 2017年5月15日 @author: louts


第1课 作业讲解及装饰器使用 28minutes


def check(func):
  def rec(request,*args,**kargs):
    return func(request,*args,**kargs)
  return rec

@check
def index(request,):
  print request

第2课 自定义装饰器扩展使用 18minutes

第3课

第4课 BBS功能分析及介绍 37minutes
  分析网站的架构
  自己写数据库Models
  参考网站的前端来写一个页面
  这节完成了页面头部的代码

第5课 BBS功能之点赞 40minutes
  按HTML分几个部分
  页头,内容,页尾
  内容中按标题,内容,通过迭代数据库内容显示出来
  参考页面写CSS和jQuery
  可以在函数中定义好几个参数
  item是数据的一条记录
  点赞{{item.favor_count}}

  

后台:
-----------------------------------------------------------------------------------
def subchat(request):
ret = {'status':0,'data':'','message':''}
try:
value = request.POST.get('data')
userobj = Admin.objects.get(id=request.session['current_user_id'])
chatobj = Chat.objects.create(content=value,user=userobj)
ret['status'] = 1
ret['data']= {'id':chatobj.id,
'username':userobj.username,
'content':chatobj.content, #这个可以不用返回,前端自己就可以获取
'create_date':chatobj.create_date.strftime('%Y-%m-%d %H:%M:%S')}
except Exception,e:
ret['message'] = e.message

return HttpResponse(json.dumps(ret))

#用于Jason序列化时间格式
class CJsonEncoder(json.JSONEncoder):
def default(self,obj):
if isinstance(obj,datetime.datetime):
return obj.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(obj,date):
return obj.strftime('%Y-%m-%d')
else:
return json,JSONEncoder.default(self,obj)

#用于前台点击评论时显示当前新闻的评论内容
def getreply(request):
id = request.POST.get('nic')
#这里可直接用外键__字段获取另一张表的内容 user__username new__id
reply_list = Reply.objcects.filter(new__id=id).values('id','content','user__username','create_date')

#json 无法序列化一个时间,可用serializers来操作
#serialize(format, queryset, **options)
'''
reply_list = serializers.serialize('json', reply_list)
return HttpResponse(reply_list)
'''
#用自己定义的类来处理时间格式
reply_list = list(reply_list)
reply_list = json.dumps(reply_list,cls=CJsonEncoder)
return HttpResponse(reply_list)


#用于前台提供评论内容


def getchart(request):
chatlist = Chat.objects.all().order_by('-id')[0:10].values('id','content','user__username','create_date')
chatlist = list(chatlist)
chatlist = json.dumps(chatlist,cls=CJsonEncoder)
return HttpResponse(chatlist)

def getchart2(request):
lastid = request.POST.get('lastid')
chatlist = Chat.objects.all().filter(id__gt=lastid).values('id','content','user__username','create_date')
chatlist = list(chatlist)
chatlist = json.dumps(chatlist,cls=CJsonEncoder)
return HttpResponse(chatlist)

 


作业:
-----------------------------------------------------------------------------------
评论样式更新
加上分页
装饰器使用,想评论可能弹跳出框,先登录,再发评论

自己可以写一个博客,将所有的内容放到上面

前台

 




	
	louts bbs page
		



	
当前登录用户:{{user}} 退出

  

  

 

后台

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render,render_to_response,HttpResponse, redirect
from models import *
import json
from django.core import serializers
from json.encoder import JSONEncoder


# Create your views here.

def index(request):
    all_data = News.objects.all()
    return render_to_response('index.html',{'data':all_data})



#用于点赞功能,点击时写到数据库中,并将数据返回给前台
def addfavor(request):
    ret = {'status':0,'data':'','message':''}
    try:
        #这块有时会出现Sock错误error: [Errno 10053]
        id = request.POST.get('id')
        newsObj = News.objects.get(id=id)
        temp = newsObj.favor_count + 1
        newsObj.favor_count = temp
        newsObj.save()
        ret['status'] = 1
        ret['data'] = temp
    except Exception,e:
        print 'error'
        ret['message'] = '页面出错了'
        print  ret['message'] 
    return HttpResponse(json.dumps(ret))


'''
#外键取数据可以用外键名称__id来操作,查询用点
#如果数据中有时间格式,Json无法序列化
#可使用Django的专用包来解决 serializers
#serializers.serialize(format, queryset)

#不能通过Reply('#reply_detail来访问Part4的内容,这样点击后会改变所有
#要通过子标签的父标签的下一个标签来找到$(doc).parent().netx()
$(doc).parent().next().first()找到子类第一个标签,可用Appen添加内容,
或ToggleClass来去掉CSS

Jquery用来迭代数据,obj是一个序列 
$.each(obj,function(k,v){
            temp = v.fields
            })
'''


def login(request):
    if request.methos == 'POST':
        username = request.POST.get('usernmae')
        password = request.POST.get('password')
        try:
            #currentObj得到是一个对象
            currentObj = Admin.objects.get(username=username,
                                     passsword=password)
        except Exception,e:
            currentObj = None
        if currentObj:
            request.session['current_user_id'] = currentObj.id
            return redirect('/index')
        else:
            return redirect('/login')
        
    return render_to_response('login.html')                    

def submitreply(request):
    ret = {'status':0,'data':'','message':''}
    try:
        id = request.POST.get('nid')
        data = request.POST.get('data')
        #获取新闻的对象
        newsObj = News.objects.get(id=id)
        obj = Reply.objects.create(content=data,
                             user=Admin.objects.get(id=request.session['current_user_id']),
                             new=newsObj)
        #评论保存后同时要更新闻的评论条目,自动加1
        temp = newsObj.reply_count + 1
        newsObj.reply_count = temp
        newsObj.save()
        #将数量放到前端的字典中
        ret['data']= {'reply_count':temp,'content':obj.content,
                      'user__name':obj.user.username,
                      'create_date':obj.create_date.strftime('%Y-%m-%d %H:%M:%S')}
        ret['status'] = 1
    except Exception,e:
        ret['message'] = e.message
        
    
    return HttpResponse(json.dumps(ret))
    
def subchat(request):
    ret = {'status':0,'data':'','message':''}
    try:
        value = request.POST.get('data')
        userobj = Admin.objects.get(id=request.session['current_user_id'])
        chatobj = Chat.objects.create(content=value,user=userobj)
        ret['status'] = 1
        ret['data']= {'id':chatobj.id,
                      'username':userobj.username,
                      'content':chatobj.content, #这个可以不用返回,前端自己就可以获取
                      'create_date':chatobj.create_date.strftime('%Y-%m-%d %H:%M:%S')}
    except Exception,e:
        ret['message'] = e.message
        
    return HttpResponse(json.dumps(ret))
        

#用于Jason序列化时间格式
class CJsonEncoder(json.JSONEncoder):
    def default(self,obj):
        if isinstance(obj,datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj,date):
            return obj.strftime('%Y-%m-%d')
        else:
            return json,JSONEncoder.default(self,obj)
        
#用于前台点击评论时显示当前新闻的评论内容       
def getreply(request):
    id = request.POST.get('nic')
    #这里可直接用外键__字段获取另一张表的内容 user__username  new__id
    reply_list = Reply.objcects.filter(new__id=id).values('id','content','user__username','create_date')
    
    #json 无法序列化一个时间,可用serializers来操作
    #serialize(format, queryset, **options)
    '''
    reply_list = serializers.serialize('json', reply_list)
    return HttpResponse(reply_list)
    '''
    #用自己定义的类来处理时间格式
    reply_list = list(reply_list)
    reply_list = json.dumps(reply_list,cls=CJsonEncoder)
    return HttpResponse(reply_list)
    

#用于前台提供评论内容


def getchat(request):
    chatlist = Chat.objects.all().order_by('-id')[0:10].values('id','content','user__username','create_date')
    chatlist = list(chatlist)
    chatlist = json.dumps(chatlist,cls=CJsonEncoder)
    return HttpResponse(chatlist)
  
def getchat2(request):
    lastid = request.POST.get('lastid')
    chatlist = Chat.objects.all().filter(id__gt=lastid).values('id','content','user__username','create_date')
    chatlist = list(chatlist)
    chatlist = json.dumps(chatlist,cls=CJsonEncoder)
    return HttpResponse(chatlist)
    

  

转载于:https://www.cnblogs.com/syother/p/6901685.html

你可能感兴趣的:(json,数据库,前端,ViewUI)