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

前言描述

主要是工作的遇到的一些小问题,记录下来备忘;详情项目可以在个中查阅
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 template

register = 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 models
import datetime
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from DjangoUeditor.models import UEditorField

class 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 JsonResponse
from django.http import HttpResponse
from twfabu.models import Item 
#from datetime import datetime
from django.utils.timezone import datetime
from 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_required
def 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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值