Django_分页设计和Ueditor配置、图文发布

来源:互联网 发布:ps3模拟器数据损坏 编辑:程序博客网 时间:2024/05/21 10:59

前言描述

主要是工作的遇到的一些小问题,记录下来备忘;详情项目可以在个中查阅
github地址_netpages

github.com/actanble/
github.com/anglecv

分页

分页的views.py中的部分内容

# set the split of news/def news_split_pages(request, page):    template = loader.get_template('jhun/news_split_page.html')    topnews = newsArticle.objects.filter(toutiao=True)    results = newsArticle.objects.filter(published=True).filter(toutiao=False).order_by('-pub_date')    i_page_start = 5 * (int(page) - 1) + 1    if i_page_start + 4 < len(results):        i_page_end = i_page_start + 4    else:        i_page_end = len(results)    topnew = {}    if (topnews):        topnew = topnews.order_by('-pub_date')[0]    elif (results):        topnew = results[0]        posts = results[i_page_start:i_page_end]    pages = [int(len(results) / 5) - 1 if len(results) % 5 == 0 else int(len(results) / 5)][0]    i_pages = [i + 1 for i in range(pages + 1)]  # how many pages need to show in html    urls = ['../news_page_'+str(i) for i in i_pages]    data = {        'results': posts,        'topnew': topnew,        'urls':urls,        'i':int(page),    }    return HttpResponse(template.render(data))def news_page(request):    return news_split_pages(request,1)

分页模板

++    {%block split-page%}        <div class="navigation1">          <ol class="wp-paginate">            <li><span class="title">Pages:</span></li>            {% for url in urls%}                {% if i == forloop.counter%}                   <li><span class="page current">{{i}}</span></li>                {% else %}                   <li><a href = {{url}} title={{  forloop.counter }} class="page"> {{forloop.counter}}</a></li>                {% endif %}            {% endfor %}              <!--<li><span class="title">当前页数:{{i}}</span></li>-->          </ol>        </div>    {% endblock %}

某个分页样式split_page.css

.navigation1 {    margin:auto auto 80px 300px;    float:center;}.wp-paginate {    padding:0;    margin:0;}.wp-paginate li {    float:left;    list-style:none;    margin:2px;    padding:0;}.wp-paginate a {    margin:0 2px;    line-height:20px;    text-align:center;    text-decoration:none;    border-radius:3px;    -moz-border-radius:3px;    float:left;    min-height:20px;    min-width:20px;    color:#858585;    border:2px #e3e3e3 solid;    border-radius:13px;    font-size:11px;}.wp-paginate a:hover {    border:2px #858585 solid;    color:#858585;}.wp-paginate .title {    color:#555;    margin:0;    margin-right:4px;    font-size:14px;}.wp-paginate .gap {    color:#999;    margin:0;    margin-right:4px;}.wp-paginate .current {    margin:0 2px;    line-height:20px;    text-align:center;    text-decoration:none;    border-radius:3px;    -moz-border-radius:3px;    float:left;    font-weight:700;    min-height:20px;    min-width:20px;    color:#262626;    border:2px #119eda solid;    border-radius:13px;    font-size:11px;    color:#119eda;}.wp-paginate .page {    margin:0;    padding:0;}.wp-paginate .prev {}.wp-paginate .next {}

PC 分页设计升级

##### /path/to/app/templatetags/pc_tag.py from django import templateregister = template.Library()from django.template.defaultfilters import stringfilter@register.filter(name="pagination")def pagination(value, page):    urls = value    page = int(page)    import re    pages = []    for x in urls:        try:            pages.append(int(re.match(".*_(\d+)/", x).group(1)))        except:            pass    print(pages)    max_page = pages[len(pages)-1]    #### 分页宗旨, 前面七个后面七个    heart_num = 7    pre_index = page - heart_num    ## pre_left = 0    pre_flag = """"""    if pre_index > 0:        ## 前面正好留住七个        pre_flag = """<li><a href="#">...</a></li>"""        pre_list = [urls[page-i-2] for i in range(heart_num)]        pre_list.reverse()    else:        pre_list = [urls[i] for i in range(page-1)]        ### pre_left = heart_num - page + 1    next_index = max_page - page -  heart_num    ## next_left = 0    next_flag = """"""    if next_index >= 0:        ## 后面能留住七个        next_flag = """<li><a href="#">...</a></li>"""        next_list = [urls[page+i] for i in range(heart_num)]    else:        next_list = [urls[i+page] for i in range(heart_num - abs(next_index))]        ### next_left = heart_num - page + 1    result_uls = """"""    result_uls += """<li><a href='""" + urls[0] + """'>&laquo;</a></li>"""    result_uls += pre_flag    res_urls = pre_list    res_urls.append(urls[page-1])    res_urls.extend(next_list)    res_pages = [int(re.match(".*_(\d+)/", x).group(1)) for x in res_urls]    print(res_pages)    for i in range(len(res_pages)):        if res_pages[i] == int(page):            result_uls += """<li class="active"><a href='"""+ res_urls[i] + """'>"""+ str(res_pages[i]) +"""</a></li>"""        else:            result_uls += """<li><a href='"""+ res_urls[i] + """'>"""+ str(res_pages[i]) +"""</a></li>"""    result_uls += next_flag    result_uls += """<li><a href='""" + urls[max_page-1] + """'>&raquo;</a></li>"""    return result_uls

html中改动

    <!-- 分页代码 -->        <div class="navigation">          <ul class="pagination">              {% load pc_tag %}              {{  urls| pagination:page | safe }}          </ul>        </div>

图文发布

要求打开后先加载历史发布的内容,再加载最近几秒的内容,用Ajax机部刷新。

views.py

### add the history of all and use ;def history(request):    lst = Item.objects.all()    length = len(lst)    max_id = len(Item.objects.all()) - 1    pid = Item.objects.all()[0]    LastPostID.objects.create(postdt=datetime.today(), postid= pid.id)    # set the zblist    zblist = []    for x in lst:        i_dir = {}        i_dir.setdefault("realname", x.realname)        i_dir.setdefault("content", x.content)        zblist.append(i_dir)    return render(request, "resource.html", {"zblist":zblist})## add data on the top;def new_append(request):    if LastPostID.objects.all() is None:        LastPostID.objects.create(postdt = datetime.today(), postid = 0)    length = len(Item.objects.all())    # the sign of last add    pid = LastPostID.objects.all()[len(LastPostID.objects.all()) - 1]    last = Item.objects.all()[0]    lst = [x for x in Item.objects.all() if x.id > pid.postid] # add_need of the data from database    # sign the date that have add    add_ls = []    for x in lst:        i_dir = {}        i_dir.setdefault("realname", x.realname)        i_dir.setdefault("content", x.content)        add_ls.append(i_dir)        LastPostID.objects.create(postdt=datetime.today(), postid=last.id)    print(add_ls)    return JsonResponse({"value":add_ls})

models.py

from django.db import modelsimport datetimefrom django.utils import timezonefrom django.utils.encoding import python_2_unicode_compatiblefrom DjangoUeditor.models import UEditorFieldclass Item(models.Model):    #img = models.ImageField(upload_to='pic', default= None)    realname = models.CharField(max_length=30, default="None")    content = UEditorField('内容', height=500, width=1200,        default='', blank=True, imagePath="uploads/images/%(basename)s_%(datetime)s.%(extname)s",        toolbars='full', filePath='uploads/files/%(basename)s_%(datetime)s.%(extname)s')    dt = models.DateTimeField('DatetimeCommit')    class Meta:        ordering = ['-id']    def __str__(self):        return str(self.dt)+"_"+str(self.realname)+":"+str(self.content)class LastPostID(models.Model):    postdt = models.DateTimeField('DatetimeCommit') ##no-use    postid = models.IntegerField()

Ajax的内容; js

<script>$(document).ready(function () {    setInterval("start_append()",3000);});function start_append(){    $.ajax({        type:"GET",        url:"/twfb/new_append", //测试用,test_list        dataType:"json",        //data: {dat:dict},        success:function(res){            var li="<ul>";            //i表示在data中的索引位置,n表示包含的信息的对象            $.each(res.value, function(i, item){                //获取对象中属性为optionsValue的值                li += ('<li><dl><dt>'+ item["realname"] + '</dt><dd><div class="img2"><p>'+item["content"]+'</p></div></dd></dl><div class="cl"></div></li>');            });            li += "</ul>";            $('#zblist').prepend(li);        }    });}</script>

views.py 升级

from django.shortcuts import render, HttpResponseRedirect, redirect# Create your views here.from django.http import JsonResponsefrom django.http import HttpResponsefrom twfabu.models import Item #from datetime import datetimefrom django.utils.timezone import datetimefrom django.contrib.auth.decorators import login_required## add data on the top;def new_append(request):    lst = [x for x in Item.objects.all() if x.id > request.session["last_dl"]]     print(lst)    # sign the date that have add    add_ls = []    for x in lst:        print("=============运行过===================")        i_dir = {}        i_dir.setdefault("realname", x.realname)        i_dir.setdefault("content", x.content)        add_ls.append(i_dir)    request.session["last_dl"] = Item.objects.all()[0].id    print(request.session.items())    return JsonResponse({"value": add_ls})@login_requireddef home(request):    lst = Item.objects.all()    # 上一次加载的内容存储到 session 中    try:        request.session['last_dl'] = Item.objects.all()[0].id    finally:        pass     # set the zblist    zblist = []    for x in lst:        i_dir = {}        i_dir.setdefault("realname", x.realname)        i_dir.setdefault("content", x.content)        zblist.append(i_dir)    if request.method == "GET":        return render(request, "twfabu/tw.html", {        "zblist": zblist,       # "form": form,        })    '''    # 用户界面下可以发布的发布框。    if request.method == "POST":        user = request.user        content = request.POST["content"]        gaim = Item.objects.create(realname=user.username, content=content, dt=datetime.now())        gaim.save()        print(gaim)        ## 在这里立马用掉了 Json、 所以注意        return HttpResponseRedirect("/tw/")        # url = request.POST.get('source_url', '/tw/')        # return HttpResponse("前台发布成功")    '''    return render(request, "twfabu/tw.html", {        "zblist": zblist,        })

CKeditor 配置 记录略。直接用成型的Ueditor;