轮播图管理

轮播图管理-轮播图页面样式实现

 

    path('banners/',views.banners,name='banners'),
    
@permission_required(perm="news.add_banner",login_url='/')
def banners(request):
    return render(request,'cms/banners.html')

.

{% extends 'cms/base.html' %}

{% block title %}
    轮播图管理
{% endblock %}

{% block head %}
    <style>
    .btn-group{
        float: left;
    }
    .tips{
        float: left;
    }
    .banner-item{
        width: 800px;
    }
    .thumbnail-group{
        float: left;
        width: 230px;
    }
    .thumbnail-group .thumbnail{
        width: 100%;
        height: 84px;
    }
    .more-group{
        float: left;
        margin-left: 20px;
        width: 500px;
    }
    </style>
    <script src="{% static 'arttemplate/template-web.js' %}"></script>
    <script src="{% static 'js/banners.min.js' %}"></script>
{% endblock %}

{% block content-header %}
    <h1>轮播图管理</h1>
{% endblock %}

{% block content %}
<div class="row">
<div class="col-md-12">
    <div class="btn-group">
        <button class="btn btn-primary" id="add-banner-btn">
            <i class="fa fa-plus"></i>
            添加轮播图
        </button>
    </div>
    <ul class="tips">
        <li>支持JPG,GIF,PNG格式,最多可上传6张</li>
        <li>比例4:1,宽度在800px以上,5M以内</li>
    </ul>
</div>
</div>
<div class="banner-list-group"></div>

<script id="banner-item" type="text/html">
{% verbatim %}
{{ if banner }}
<div class="box banner-item" data-banner-id="{{ banner.id }}">
{{ else }}
<div class="box banner-item">
{{ /if }}
    <div class="box-header">
        {{ if banner }}
            <span class="priority">优先级:{{ banner.priority }}</span>
        {{ else }}
            <span class="priority">优先级:0</span>
        {{ /if }}
        <button class="btn btn-default btn-xs pull-right close-btn">
            <i class="fa fa-close"></i>
        </button>
    </div>
    <div class="box-body">
        <div class="thumbnail-group">
            <input type="file" style="display: none;" class="image-input">
            {{ if banner }}
                <img src="{{ banner.image_url }}" alt="" class="thumbnail">
            {{ else }}
                <img src="/static/images/banner.png" alt="" class="thumbnail">
            {{ /if }}
        </div>
        <div class="more-group">
            <div class="form-group">
                {{ if banner }}
                    <input type="number" class="form-control" name="priority" value="{{ banner.priority }}">
                {{ else }}
                    <input type="number" class="form-control" name="priority">
                {{ /if }}
            </div>
            <div class="form-group">
                {{ if banner }}
                    <input type="text" class="form-control" name="link_to" value="{{ banner.link_to }}">
                {{ else }}
                    <input type="text" class="form-control" name="link_to">
            </div>
            {{ /if }}
        </div>
    </div>
    <div class="box-footer">
        <button class="btn btn-primary pull-right save-btn">保存</button>
    </div>
</div>
{% endverbatim %}
</script>
{% endblock %}

轮播图管理-添加轮播图卡片事件

 

Banners.prototype.listenAddBannerEvent = function () {
    var self = this;
    var addBtn = $("#add-banner-btn");
    addBtn.click(function () {
        var bannerListGroup = $('.banner-list-group');
        var length = bannerListGroup.children().length;
        if(length >= 6){
            window.messageBox.showInfo('最多只能添加6张轮播图!');
            return;
        }
        self.createBannerItem();
    });
};
<div class="banner-list-group"></div>
{% verbatim %}
{{ if banner }}
<div class="box banner-item" data-banner-id="{{ banner.id }}">
{{ else }}
<div class="box banner-item">
{{ /if }}
    <div class="box-header">
        {{ if banner }}
            <span class="priority">优先级:{{ banner.priority }}</span>
        {{ else }}
            <span class="priority">优先级:0</span>
        {{ /if }}
        <button class="btn btn-default btn-xs pull-right close-btn">
            <i class="fa fa-close"></i>
        </button>
    </div>
    <div class="box-body">
        <div class="thumbnail-group">
            <input type="file" style="display: none;" class="image-input">
            {{ if banner }}
                <img src="{{ banner.image_url }}" alt="" class="thumbnail">
            {{ else }}
                <img src="/static/images/banner.png" alt="" class="thumbnail">
            {{ /if }}
        </div>
        <div class="more-group">
            <div class="form-group">
                {{ if banner }}
                    <input type="number" class="form-control" name="priority" value="{{ banner.priority }}">
                {{ else }}
                    <input type="number" class="form-control" name="priority">
                {{ /if }}
            </div>
            <div class="form-group">
                {{ if banner }}
                    <input type="text" class="form-control" name="link_to" value="{{ banner.link_to }}">
                {{ else }}
                    <input type="text" class="form-control" name="link_to">
            </div>
            {{ /if }}
        </div>
    </div>
    <div class="box-footer">
        <button class="btn btn-primary pull-right save-btn">保存</button>
    </div>
</div>
{% endverbatim %}

轮播图管理-轮播图上传功能完成

 

Banners.prototype.addImageSelectEvent = function (bannerItem) {
    var image = bannerItem.find('.thumbnail');
    var imageInput = bannerItem.find('.image-input');
    // 图片是不能够打开文件选择框的,只能通过input[type='file']
    image.click(function () {
        imageInput.click();
    });

    imageInput.change(function () {
        var file = this.files[0];
        var formData = new FormData();
        formData.append("file",file);
        xfzajax.post({
            'url': '/cms/upload_file/',
            'data': formData,
            'processData': false,
            'contentType': false,
            'success': function (result) {
                if(result['code'] === 200){
                    var url = result['data']['url'];
                    image.attr('src',url);
                }
            }
        });
    });
};

<div class="thumbnail-group">
            <input type="file" style="display: none;" class="image-input">  //file类型
            {{ if banner }}
                <img src="{{ banner.image_url }}" alt="" class="thumbnail">
            {{ else }}
                <img src="/static/images/banner.png" alt="" class="thumbnail">
            {{ /if }}
        </div>

轮播图管理-轮播图卡片关闭事件

 

Banners.prototype.addRemoveBannerEvent = function (bannerItem) {
    var closeBtn = bannerItem.find('.close-btn');

    closeBtn.click(function () {
        var bannerId = bannerItem.attr('data-banner-id');
        if(bannerId){
            xfzalert.alertConfirm({
                'text': '您确定要删除这个轮播图吗?',
                'confirmCallback': function () {
                    xfzajax.post({
                        'url': '/cms/delete_banner/',
                        'data': {
                            'banner_id': bannerId
                        },
                        'success': function (result) {
                            if(result['code'] === 200){
                                bannerItem.remove();
                                window.messageBox.showSuccess('轮播图删除才成功!');
                            }
                        }
                    });
                }
            });
        }else{
            bannerItem.remove();
        }
    });
};

轮播图管理-添加轮播图功能完成

 

class Banner(models.Model):
    priority = models.IntegerField(default=0)
    image_url = models.URLField()
    link_to = models.URLField()
    pub_time = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-priority']
@permission_required(perm="news.add_banner",login_url='/')
def add_banner(request):
    form = AddBannerForm(request.POST)
    if form.is_valid():
        priority = form.cleaned_data.get('priority')
        image_url = form.cleaned_data.get('image_url')
        link_to = form.cleaned_data.get('link_to')
        banner = Banner.objects.create(priority=priority,image_url=image_url,link_to=link_to)
        return restful.result(data={"banner_id":banner.pk})
    else:
        return restful.params_error(message=form.get_errors())
Banners.prototype.addSaveBannerEvent = function (bannerItem) {
    var saveBtn = bannerItem.find('.save-btn');
    var imageTag = bannerItem.find(".thumbnail");
    var priorityTag = bannerItem.find("input[name='priority']");
    var linktoTag = bannerItem.find("input[name='link_to']");
    var prioritySpan = bannerItem.find('span[class="priority"]');
    var bannerId = bannerItem.attr("data-banner-id");
    var url = '';
    if(bannerId){
        url = '/cms/edit_banner/';
    }else{
        url = '/cms/add_banner/';
    }
    saveBtn.click(function () {
        var image_url = imageTag.attr('src');
        var priority = priorityTag.val();
        var link_to = linktoTag.val();
        xfzajax.post({
            'url': url,
            'data':{
                'image_url': image_url,
                'priority': priority,
                'link_to': link_to,
                'pk': bannerId
            },
            'success': function (result) {
                if(result['code'] === 200){
                    if(bannerId){
                        window.messageBox.showSuccess('轮播图修改成功!');
                    }else{
                        bannerId = result['data']['banner_id'];
                        bannerItem.attr('data-banner-id',bannerId);
                        window.messageBox.showSuccess('轮播图添加完成!');
                    }
                    prioritySpan.text("优先级:"+priority);
                }
            }
        });
    });
};

轮播图管理-异步加载轮播图列表

 


class BannerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Banner
        fields = ('id','image_url','priority','link_to')
@permission_required(perm="news.add_banner",login_url='/')
def banner_list(request):
    banners = Banner.objects.all()
    serialize = BannerSerializer(banners,many=True)
    return restful.result(data=serialize.data)
Banners.prototype.loadData = function () {
    var self = this;
    xfzajax.get({
        'url': '/cms/banner_list/',
        'success': function (result) {
            if(result['code'] === 200){
                var banners = result['data'];
                console.log(banners);
                for(var i=0; i<banners.length;i++){
                    var banner = banners[i];
                    self.createBannerItem(banner);
                }
            }
        }
    });
}
Banners.prototype.createBannerItem = function (banner) {
    var self = this;
    var tpl = template("banner-item",{"banner":banner});
    var bannerListGroup = $(".banner-list-group");

    var bannerItem = null;
    if(banner){
        bannerListGroup.append(tpl);
        bannerItem = bannerListGroup.find(".banner-item:last");
    }else{
        bannerListGroup.prepend(tpl);
        bannerItem = bannerListGroup.find(".banner-item:first");
    }
    self.addImageSelectEvent(bannerItem);
    self.addRemoveBannerEvent(bannerItem);
    self.addSaveBannerEvent(bannerItem);
};

轮播图管理-轮播图删除功能完成

 

Banners.prototype.addRemoveBannerEvent = function (bannerItem) {
    var closeBtn = bannerItem.find('.close-btn');

    closeBtn.click(function () {
        var bannerId = bannerItem.attr('data-banner-id');
        if(bannerId){
            xfzalert.alertConfirm({
                'text': '您确定要删除这个轮播图吗?',
                'confirmCallback': function () {
                    xfzajax.post({
                        'url': '/cms/delete_banner/',
                        'data': {
                            'banner_id': bannerId
                        },
                        'success': function (result) {
                            if(result['code'] === 200){
                                bannerItem.remove();
                                window.messageBox.showSuccess('轮播图删除才成功!');
                            }
                        }
                    });
                }
            });
        }else{
            bannerItem.remove();
        }
    });
};
@permission_required(perm="news.delete_banner",login_url='/')
def delete_banner(request):
    banner_id = request.POST.get('banner_id')
    Banner.objects.filter(pk=banner_id).delete()
    return restful.ok()

轮播图管理-修改轮播图和限制轮播图个数

 


class EditBannerForm(forms.ModelForm,FormMixin):
    pk = forms.IntegerField()
    class Meta:
        model = Banner
        fields = ('priority','link_to','image_url')
@permission_required(perm="news.change_banner",login_url='/')
def edit_banner(request):
    form = EditBannerForm(request.POST)
    if form.is_valid():
        pk = form.cleaned_data.get('pk')
        image_url = form.cleaned_data.get('image_url')
        link_to = form.cleaned_data.get('link_to')
        priority = form.cleaned_data.get('priority')
        Banner.objects.filter(pk=pk).update(image_url=image_url,link_to=link_to,priority=priority)
        return restful.ok()
    else:
        return restful.params_error(message=form.get_errors())

    path('edit_banner/',views.edit_banner,name='edit_banner'),
Banners.prototype.addSaveBannerEvent = function (bannerItem) {
    var saveBtn = bannerItem.find('.save-btn');
    var imageTag = bannerItem.find(".thumbnail");
    var priorityTag = bannerItem.find("input[name='priority']");
    var linktoTag = bannerItem.find("input[name='link_to']");
    var prioritySpan = bannerItem.find('span[class="priority"]');
    var bannerId = bannerItem.attr("data-banner-id");
    var url = '';
    if(bannerId){
        url = '/cms/edit_banner/';
    }else{
        url = '/cms/add_banner/';
    }
    saveBtn.click(function () {
        var image_url = imageTag.attr('src');
        var priority = priorityTag.val();
        var link_to = linktoTag.val();
        xfzajax.post({
            'url': url,
            'data':{
                'image_url': image_url,
                'priority': priority,
                'link_to': link_to,
                'pk': bannerId
            },
            'success': function (result) {
                if(result['code'] === 200){
                    if(bannerId){
                        window.messageBox.showSuccess('轮播图修改成功!');
                    }else{
                        bannerId = result['data']['banner_id'];
                        bannerItem.attr('data-banner-id',bannerId);
                        window.messageBox.showSuccess('轮播图添加完成!');
                    }
                    prioritySpan.text("优先级:"+priority);
                }
            }
        });
    });
};
Banners.prototype.listenAddBannerEvent = function () {
    var self = this;
    var addBtn = $("#add-banner-btn");
    addBtn.click(function () {
        var bannerListGroup = $('.banner-list-group');
        var length = bannerListGroup.children().length;
        if(length >= 6){
            window.messageBox.showInfo('最多只能添加6张轮播图!');
            return;
        }
        self.createBannerItem();
    });
};

解决移除新增轮播图小bug

 

首页轮播图数据修改和bug解决

 

新闻管理-新闻列表和查询条件布局完成

 

{% extends 'cms/base.html' %}
{% load news_filters %}

{% block title %}
    新闻列表
{% endblock %}

{% block head %}
    <style>
    .left-group{
        margin-right: 20px;
    }
    </style>
    <link rel="stylesheet" href="{% static 'adminlte/bower_components/bootstrap-datepicker/dist/css/bootstrap-datepicker.min.css' %}">
    <script src="{% static 'adminlte/bower_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js' %}"></script>
    <script src="{% static 'adminlte/bower_components/bootstrap-datepicker/dist/locales/bootstrap-datepicker.zh-CN.min.js' %}"></script>
    <script src="{% static 'js/news_list.min.js' %}"></script>
{% endblock %}

{% block content-header %}
    <h1>新闻列表管理</h1>
{% endblock %}

{% block content %}
<div class="row">
<div class="col-md-12">
    <div class="box">
        <div class="box-header">
            <form action="" method="get" class="form-inline">
                <div class="form-group left-group">
                    <label for="">时间:</label>
                    {% if start %}
                        <input type="text" class="form-control" name="start" placeholder="起始时间" id="start-picker" readonly value="{{ start }}">
                    {% else %}
                        <input type="text" class="form-control" name="start" placeholder="起始时间" id="start-picker" readonly>
                    {% endif %}
                    <span>—</span>
                    {% if end %}
                        <input type="text" id="end-picker" class="form-control" name="end" placeholder="结束时间" readonly value="{{ end }}">
                    {% else %}
                        <input type="text" id="end-picker" class="form-control" name="end" placeholder="结束时间" readonly>
                    {% endif %}
                </div>
                <div class="form-group left-group">
                    <label for="title-input">标题:</label>
                    {% if title %}
                        <input type="text" class="form-control" name="title" id="title-input" placeholder="关键字" value="{{ title }}">
                    {% else %}
                        <input type="text" class="form-control" name="title" id="title-input" placeholder="关键字">
                    {% endif %}
                </div>
                <div class="form-group left-group">
                    <label for="category-input">分类:</label>
                    <select name="category" id="" class="form-control">
                        {% if category_id == 0 %}
                            <option value="0" selected>所有分类</option>
                        {% else %}
                            <option value="0">所有分类</option>
                        {% endif %}
                        {% for category in categories %}
                            {% if category_id == category.pk %}
                                <option value="{{ category.pk }}" selected>{{ category.name }}</option>
                            {% else %}
                                <option value="{{ category.pk }}">{{ category.name }}</option>
                            {% endif %}
                        {% endfor %}
                    </select>
                </div>
                <div class="form-group left-group">
                    <button class="btn btn-primary">查询</button>
                </div>
                <div class="form-group">
                    <a href="{% url 'cms:news_list' %}">清除查询</a>
                </div>
            </form>
        </div>
        <div class="box-body">
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>标题</th>
                        <th>分类</th>
                        <th>发布时间</th>
                        <th>作者</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for news in newses %}
                        <tr>
                            <td><a target="_blank" href="{% url 'news:news_detail' news_id=news.pk %}">{{ news.title }}</a></td>
                            <td>{{ news.category.name }}</td>
                            <td>{{ news.pub_time|time_format }}</td>
                            <td>{{ news.author.username }}</td>
                            <td>
                                <a href="{% url 'cms:edit_news' %}?news_id={{ news.pk }}" class="btn btn-info btn-xs">编辑</a>
                                <button class="btn btn-danger btn-xs delete-btn" data-news-id="{{ news.pk }}">删除</button>
                            </td>
                        </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        <div class="box-footer">
            <p class="pull-left">第{{ current_page }}/总共{{ num_pages }}页</p>
            <ul class="pagination pull-right">
                {#上一页#}
                {% if page_obj.has_previous %}
                    <li><a href="?p={{ page_obj.previous_page_number }}{{ url_query }}">上一页</a></li>
                {% else %}
                    <li class="disabled"><a href="javascript:void(0);">上一页</a></li>
                {% endif %}

                {# 是否需要出现三个点 #}
                {% if left_has_more %}
                    <li><a href="?p=1">1</a></li>
                    <li><a href="javascript:void(0);">...</a></li>
                {% endif %}

                {# 左边的页码 #}
                {% for left_page in left_pages %}
                    <li><a href="?p={{ left_page }}{{ url_query }}">{{ left_page }}</a></li>
                {% endfor %}

                {# 当前的页面 #}
                <li class="active"><a href="?p={{ current_page }}{{ url_query }}">{{ current_page }}</a></li>

                {# 右边的页码 #}
                {% for right_page in right_pages %}
                    <li><a href="?p={{ right_page }}{{ url_query }}">{{ right_page }}</a></li>
                {% endfor %}

                {# 用来控制右边三个点 #}
                {% if right_has_more %}
                    <li><a href="javascript:void(0);">...</a></li>
                    <li><a href="?p={{ num_pages }}{{ url_query }}">{{ num_pages }}</a></li>
                {% endif %}

                {#下一页#}
                {% if page_obj.has_next %}
                    <li><a href="?p={{ page_obj.next_page_number }}{{ url_query }}">下一页</a></li>
                {% else %}
                    <li class="disabled"><a href="javascript:void(0);">下一页</a></li>
                {% endif %}
            </ul>
        </div>
    </div>
</div>
</div>
{% endblock %}

400 700 3030
400 699 3030

新闻管理-实现新闻分页功能

 

<div class="box-footer">
            <p class="pull-left">第{{ current_page }}/总共{{ num_pages }}页</p>
            <ul class="pagination pull-right">
                {#上一页#}
                {% if page_obj.has_previous %}
                    <li><a href="?p={{ page_obj.previous_page_number }}{{ url_query }}">上一页</a></li>
                {% else %}
                    <li class="disabled"><a href="javascript:void(0);">上一页</a></li>
                {% endif %}

                {# 是否需要出现三个点 #}
                {% if left_has_more %}
                    <li><a href="?p=1">1</a></li>
                    <li><a href="javascript:void(0);">...</a></li>
                {% endif %}

                {# 左边的页码 #}
                {% for left_page in left_pages %}
                    <li><a href="?p={{ left_page }}{{ url_query }}">{{ left_page }}</a></li>
                {% endfor %}

                {# 当前的页面 #}
                <li class="active"><a href="?p={{ current_page }}{{ url_query }}">{{ current_page }}</a></li>

                {# 右边的页码 #}
                {% for right_page in right_pages %}
                    <li><a href="?p={{ right_page }}{{ url_query }}">{{ right_page }}</a></li>
                {% endfor %}

                {# 用来控制右边三个点 #}
                {% if right_has_more %}
                    <li><a href="javascript:void(0);">...</a></li>
                    <li><a href="?p={{ num_pages }}{{ url_query }}">{{ num_pages }}</a></li>
                {% endif %}

                {#下一页#}
                {% if page_obj.has_next %}
                    <li><a href="?p={{ page_obj.next_page_number }}{{ url_query }}">下一页</a></li>
                {% else %}
                    <li class="disabled"><a href="javascript:void(0);">下一页</a></li>
                {% endif %}
            </ul>
        </div>
@method_decorator(permission_required(perm="news.change_news",login_url='/'),name='dispatch')
class NewsListView(View):
    def get(self,request):
        # request.GET:获取出来的所有数据,都是字符串类型
        page = int(request.GET.get('p',1))
        start = request.GET.get('start')
        end = request.GET.get('end')
        title = request.GET.get('title')
        # request.GET.get(参数,默认值)
        # 这个默认值是只有这个参数没有传递的时候才会使用
        # 如果传递了,但是是一个空的字符串,那么也不会使用默认值
        category_id = int(request.GET.get('category',0) or 0)

        newses = News.objects.select_related('category', 'author')

        if start or end:
            if start:
                start_date = datetime.strptime(start,'%Y/%m/%d')
            else:
                start_date = datetime(year=2018,month=6,day=1)
            if end:
                end_date = datetime.strptime(end,'%Y/%m/%d')
            else:
                end_date = datetime.today()
            newses = newses.filter(pub_time__range=(make_aware(start_date),make_aware(end_date)))

        if title:
            newses = newses.filter(title__icontains=title)

        if category_id:
            newses = newses.filter(category=category_id)

        paginator = Paginator(newses, 2)
        page_obj = paginator.page(page)

        context_data = self.get_pagination_data(paginator,page_obj)

        context = {
            'categories': NewsCategory.objects.all(),
            'newses': page_obj.object_list,
            'page_obj': page_obj,
            'paginator': paginator,
            'start': start,
            'end': end,
            'title': title,
            'category_id': category_id,
            'url_query': '&'+parse.urlencode({
                'start': start or '',
                'end': end or '',
                'title': title or '',
                'category': category_id or ''
            })
        }

        print('='*30)
        print(category_id)
        print('='*30)

        context.update(context_data)

        return render(request, 'cms/news_list.html', context=context)

时间选择器控件的集成

 

CMSNewsList.prototype.initDatePicker = function () {
    var startPicker = $("#start-picker");
    var endPicker = $("#end-picker");

    var todayDate = new Date();
    var todayStr = todayDate.getFullYear() + '/' + (todayDate.getMonth()+1) + '/' + todayDate.getDate();
    var options = {
        'showButtonPanel': true,
        'format': 'yyyy/mm/dd',
        'startDate': '2017/6/1',
        'endDate': todayStr,
        'language': 'zh-CN',
        'todayBtn': 'linked',
        'todayHighlight': true,
        'clearBtn': true,
        'autoclose': true
    };
    startPicker.datepicker(options);
    endPicker.datepicker(options);
};

根据时间、标题、分类查询新闻并分页显示

 

    def get(self,request):
        # request.GET:获取出来的所有数据,都是字符串类型
        page = int(request.GET.get('p',1))
        start = request.GET.get('start')
        end = request.GET.get('end')
        title = request.GET.get('title')
        # request.GET.get(参数,默认值)
        # 这个默认值是只有这个参数没有传递的时候才会使用
        # 如果传递了,但是是一个空的字符串,那么也不会使用默认值
        category_id = int(request.GET.get('category',0) or 0)

        newses = News.objects.select_related('category', 'author')

        if start or end:
            if start:
                start_date = datetime.strptime(start,'%Y/%m/%d')
            else:
                start_date = datetime(year=2018,month=6,day=1)
            if end:
                end_date = datetime.strptime(end,'%Y/%m/%d')
            else:
                end_date = datetime.today()
            newses = newses.filter(pub_time__range=(make_aware(start_date),make_aware(end_date)))

        if title:
            newses = newses.filter(title__icontains=title)

        if category_id:
            newses = newses.filter(category=category_id)

将文章发布时间格式化为本地时间

 

@register.filter
def time_format(value):
    if not isinstance(value,datetime):
        return value

    return localtime(value).strftime("%Y/%m/%d %H:%M:%S")

编辑新闻功能完成

 

@method_decorator(permission_required(perm="news.change_news",login_url='/'),name='dispatch')
class EditNewsView(View):
    def get(self,request):
        news_id = request.GET.get('news_id')
        news = News.objects.get(pk=news_id)
        context = {
            'news': news,
            'categories': NewsCategory.objects.all()
        }
        return render(request,'cms/write_news.html',context=context)

    def post(self,request):
        form = EditNewsForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data.get('title')
            desc = form.cleaned_data.get('desc')
            thumbnail = form.cleaned_data.get('thumbnail')
            content = form.cleaned_data.get('content')
            category_id = form.cleaned_data.get('category')
            pk = form.cleaned_data.get("pk")
            category = NewsCategory.objects.get(pk=category_id)
            News.objects.filter(pk=pk).update(title=title,desc=desc,thumbnail=thumbnail,content=content,category=category)
            return restful.ok()
        else:
            return restful.params_error(message=form.get_errors())
class EditNewsForm(forms.ModelForm,FormMixin):
    category = forms.IntegerField()
    pk = forms.IntegerField()
    class Meta:
        model = News
        exclude = ['category','author','pub_time']

删除新闻功能完成

 

@require_POST
@permission_required(perm="news.delete_news",login_url='/')
def delete_news(request):
    news_id = request.POST.get('news_id')
    News.objects.filter(pk=news_id).delete()
    return restful.ok()
CMSNewsList.prototype.listenDeleteEvent = function () {
    var deleteBtns = $(".delete-btn");
    deleteBtns.click(function () {
        var btn = $(this);
        var news_id = btn.attr('data-news-id');
        xfzalert.alertConfirm({
            'text': '您是否要删除这篇新闻吗?',
            'confirmCallback': function () {
                xfzajax.post({
                    'url': '/cms/delete_news/',
                    'data': {
                        'news_id': news_id
                    },
                    'success': function (result) {
                        if(result['code'] === 200){
                            window.location = window.location.href;
                            // window.location.reload()
                        }
                    }
                });
            }
        });
    });
};