热门文章搜索功能
1.分析
请求方法:GET
url定义: /admin/hotnews/
- views.py
class HotNewsManageView(PermissionRequiredMixin, View):
"""
渲染热门文章页
"""
permission_required = ('news.view_hotnews',)
raise_exception = True
def get(self,request):
hot_news = models.HotNews.objects.select_related('news__tag').\
only('news_id','news__title','news__tag__name','priority').\
filter(is_delete=False).order_by('priority','-news__clicks')[0:SHOW_HOTNEWS_COUNT]
return render(request, 'admin/news/news_hot.html', locals())
- urls.py
path('hotnews/', views.HotNewsManageView.as_view(), name='hotnews_manage'),
- html
<!-- 创建templates/admin/news/news_hot.html文件 -->
{% extends 'admin/base/base.html' %}
{% block title %}
热门文章管理页面
{% endblock %}
{% block content_header %}
热门文章管理
{% endblock %}
{% block header_option_desc %}
正确的决策来自众人的智慧
{% endblock %}
{% block content %}
<div class="row">
<div class="col-md-12 col-xs-12 col-sm-12">
<div class="box box-primary">
<div class="box-header">
<a href="{% url 'admin:hotnews_add' %}" class="btn btn-primary pull-right"
id="btn-add-news-recommend">添加热门文章</a>
</div>
<div class="box-body">
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>文章名称</th>
<th>文章分类</th>
<th>优先级</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for hot_new in hot_news %}
<tr data-id="{{ hot_new.id }}" data-name="{{ hot_new.news.title }}">
<td>
<a href="{% url 'news:news_detail' hot_new.news_id %}" data-news-id="{{ hot_new.news_id }}">
{{ hot_new.news.title }}
</a>
</td>
<td>{{ hot_new.news.tag.name }}</td>
<!-- 该处可以打断点找到一种可以显示中文的方法 get_priority_display -->
<!-- 当我们想要获取参数时,但却不知道什么方法可以通过打断点得到 -->
<!-- 模板中需要调用一个方法是不需要() -->
<td>{{ hot_new.priority }}</td>
<td>
<button class="btn btn-xs btn-warning btn-edit"
data-priority="{{ hot_new.priority }}">编辑</button>
<button class="btn btn-xs btn-danger btn-del">删除</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="box-footer"></div>
</div>
</div>
</div>
{% endblock %}
{% block script %}
<script src="/static/js/admin/news/news_hot.js"></script>
{% endblock %}
热门文章编辑功能
1.分析
请求方法:PUT、DETELE
url定义: 'hotnews/<int:hotnews_id>/'
# 热门文章编辑功能
class HotNewsEditView(PermissionRequiredMixin,View):
"""
"""
permission_required = ('news.change_hotnews','news.delete_hotnews')
raise_exception = True
def handle_no_permission(self):
if self.request.method.lower() != 'get':
return to_json_data(errno=Code.ROLEERR, errmsg='没有操作权限')
else:
return super(HotNewsEditView, self).handle_no_permission()
def delete(self, request, hotnews_id):
hotnews = models.HotNews.objects.only('id').filter(id=hotnews_id).first()
if hotnews:
hotnews.is_delete = True
hotnews.save(update_fields = ['is_delete'])
return to_json_data(errmsg="热门文章删除成功")
else:
return to_json_data(errno=Code.PARAMERR, errmsg="需要删除的热门文章不存在")
def put(self, request, hotnews_id):
hotnews = models.HotNews.objects.only('id','is_delete').filter(is_delete=False,id=hotnews_id).first()
if not hotnews:
return to_json_data(errno=Code.PARAMERR, errmsg="需要更新的热门文章不存在")
json_data = request.body
if not json_data:
return to_json_data(errno=Code.PARAMERR, errmsg=error_map[Code.PARAMERR])
# 将json转化为dict
dict_data = json.loads(json_data.decode('utf8'))
try:
priority = int(dict_data.get('priority'))
priority_list = [i for i, _ in models.HotNews.PRI_CHOICES]
if priority not in priority_list:
return to_json_data(errno=Code.PARAMERR, errmsg='热门文章的优先级设置错误')
except Exception as e:
logger.info('热门文章优先级异常:\n{}'.format(e))
return to_json_data(errno=Code.PARAMERR, errmsg='热门文章的优先级设置错误')
if hotnews.priority == priority:
return to_json_data(errno=Code.PARAMERR, errmsg="热门文章的优先级未改变")
hotnews.priority = priority
hotnews.save(update_fields=['priority'])
return to_json_data(errmsg="热门文章更新成功")
- html
// 创建static/js/admin/news/news_hot.js文件
$(function () {
// 添加热门文章
let $tagAdd = $("#btn-add-tag"); // 1. 获取添加按钮
$tagAdd.click(function () { // 2. 点击事件
fAlert.alertOneInput({
title: "请输入文章标签",
text: "长度限制在20字以内",
placeholder: "请输入文章标签",
confirmCallback: function confirmCallback(inputVal) {
console.log(inputVal);
if (inputVal === "") {
swal.showInputError('标签不能为空');
return false;
}
let sDataParams = {
"name": inputVal
};
$.ajax({
// 请求地址
url: "/admin/tags/", // url尾部需要添加/
// 请求方式
type: "POST",
data: JSON.stringify(sDataParams),
// 请求内容的数据类型(前端发给后端的格式)
contentType: "application/json; charset=utf-8",
// 响应数据的格式(后端返回给前端的格式)
dataType: "json",
})
.done(function (res) {
if (res.errno === "200") {
fAlert.alertSuccessToast(inputVal + " 标签添加成功");
setTimeout(function () {
window.location.reload();
}, 1000)
} else {
swal.showInputError(res.errmsg);
}
})
.fail(function () {
message.showError('服务器超时,请重试!');
});
}
});
});
// 编辑热门文章
let $HotNewsEdit = $(".btn-edit"); // 1. 获取编辑按钮
$HotNewsEdit.click(function () { // 2. 点击触发事件
let _this = this;
let sHotNewsId = $(this).parents('tr').data('id');
// let sHotNewsTitle = $(this).parents('tr').data('name');
let sPriority = $(this).data('priority');
fAlert.alertOneInput({
title: "编辑热门文章优先级",
text: "你正在编辑热门文章的优先级",
placeholder: "请输入文章优先级",
value: sPriority,
confirmCallback: function confirmCallback(inputVal) {
if (!inputVal.trim()) {
swal.showInputError('输入框不能为空!');
return false;
// == 和 === 区别 用户输入的是字符串,数据库是整形int,所以用==,只判断值
} else if (inputVal == sPriority) {
swal.showInputError('优先级未修改');
return false;
} else if (!jQuery.inArray(inputVal, ['1', '2', '3'])) {
swal.showInputError('优先级只能取1,2,3中的一个');
return false;
}
let sDataParams = {
"priority": inputVal
};
$.ajax({
// 请求地址
url: "/admin/hotnews/" + sHotNewsId + "/", // url尾部需要添加/
// 请求方式
type: "PUT",
data: JSON.stringify(sDataParams),
// 请求内容的数据类型(前端发给后端的格式)
contentType: "application/json; charset=utf-8",
// 响应数据的格式(后端返回给前端的格式)
dataType: "json",
})
.done(function (res) {
if (res.errno === "200") {
swal.close();
message.showSuccess("标签修改成功");
// $(_this).parents('tr').find('td:nth-child(3)').text(inputVal);
setTimeout(function () {
window.location.href = '/admin/hotnews/';
}, 800)
} else {
swal.showInputError(res.errmsg);
}
})
.fail(function () {
message.showError('服务器超时,请重试!');
});
}
});
});
// 删除热门文章
let $HotNewsDel = $(".btn-del"); // 1. 获取删除按钮
$HotNewsDel.click(function () { // 2. 点击触发事件
let _this = this;
let sHotNewsId = $(this).parents('tr').data('id');
fAlert.alertConfirm({
title: "确定删除热门文章吗?",
type: "error",
confirmText: "确认删除",
cancelText: "取消删除",
confirmCallback: function confirmCallback() {
$.ajax({
url: "/admin/hotnews/" + sHotNewsId + "/", // url尾部需要添加/
type: "DELETE",
dataType: "json",
})
.done(function (res) {
if (res.errno === "200") {
message.showSuccess("删除热门文章成功");
$(_this).parents('tr').remove();
setTimeout(function () {
window.location.href = '/admin/hotnews/';
}, 800)
} else {
swal.showInputError(res.errmsg);
}
})
.fail(function () {
message.showError('服务器超时,请重试!');
});
}
});
});
// get cookie using jQuery
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
let cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
let cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
// Setting the token on the AJAX request
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
});
热门文章发布功能
1.分析
请求方法:GET、POST
url定义: 'hotnews/add/'
from collections import OrderedDict
class HotNewsAddView(PermissionRequiredMixin, View):
"""
route: /admin/hotnews/add/
"""
permission_required = ('news.add_hotnews', 'news.view_hotnews')
raise_exception = True
def handle_no_permission(self):
if self.request.method.lower() != 'get':
return to_json_data(errno=Code.ROLEERR, errmsg='没有操作权限')
else:
return super(HotNewsAddView, self).handle_no_permission()
def get(self, request):
tags = models.Tag.objects.values('id', 'name').annotate(num_news=Count('news')). \
filter(is_delete=False).order_by('-num_news', 'update_time')
# 优先级列表
# priority_list = {K: v for k, v in models.HotNews.PRI_CHOICES}
# OrderedDict 将嵌套元祖构造成字典
priority_dict = OrderedDict(models.HotNews.PRI_CHOICES)
return render(request, 'admin/news/news_hot_add.html', locals())
def post(self, request):
json_data = request.body
if not json_data:
return to_json_data(errno=Code.PARAMERR, errmsg=error_map[Code.PARAMERR])
# 将json转化为dict
dict_data = json.loads(json_data.decode('utf8'))
try:
news_id = int(dict_data.get('news_id'))
except Exception as e:
logger.info('前端传过来的文章id参数异常:\n{}'.format(e))
return to_json_data(errno=Code.PARAMERR, errmsg='参数错误')
if not models.News.objects.filter(id=news_id).exists():
return to_json_data(errno=Code.PARAMERR, errmsg='文章不存在')
try:
priority = int(dict_data.get('priority'))
priority_list = [i for i, _ in models.HotNews.PRI_CHOICES]
if priority not in priority_list:
return to_json_data(errno=Code.PARAMERR, errmsg='热门文章的优先级设置错误')
except Exception as e:
logger.info('热门文章优先级异常:\n{}'.format(e))
return to_json_data(errno=Code.PARAMERR, errmsg='热门文章的优先级设置错误')
# 创建热门新闻
hotnews_tuple = models.HotNews.objects.get_or_create(news_id=news_id)
hotnews, is_created = hotnews_tuple
hotnews.priority = priority # 修改优先级
hotnews.save(update_fields=['priority'])
return to_json_data(errmsg="热门文章创建成功")
- 点击文章标签查询文章
1.分析
请求方法:GET
url定义: 'tags/<int:tag_id>/news/'
class NewsByTagIdView(PermissionRequiredMixin, View):
"""
route: /admin/tags/<int:tag_id>/news/
"""
permission_required = ('news.view_news', 'news.add_hotnews')
# raise_exception = True
def handle_no_permission(self):
return to_json_data(errno=Code.ROLEERR, errmsg='没有操作权限')
def get(self, request, tag_id):
newses = models.News.objects.values('id', 'title').filter(is_delete=False, tag_id=tag_id)
news_list = [i for i in newses]
return to_json_data(data={
'news': news_list
})
- urls.py
path('hotnews/', views.HotNewsManageView.as_view(), name='hotnews_manage'),
path('hotnews/<int:hotnews_id>/', views.HotNewsEditView.as_view(), name='hotnews_edit'),
path('hotnews/add/', views.HotNewsAddView.as_view(), name='hotnews_add'),
path('tags/<int:tag_id>/news/', views.NewsByTagIdView.as_view(), name='news_by_tagid'),
- html
{% extends 'admin/base/base.html' %}
{% block title %}
添加热门文章
{% endblock %}
{% block content_header %}
添加热门文章
{% endblock %}
{% block header_option_desc %}
创建热门文章
{% endblock %}
{% block content %}
<div class="box box-primary">
<div class="box-body">
<div class="form-horizontal">
<div class="form-group">
<label for="category-select" class="col-md-2 col-sm-2 control-label">选择文章</label>
<div class="col-md-2 col-sm-3">
<select name="category" id="category-select" class="form-control input-md">
<option value="0">--请选择文章分类--</option>
{% for one_tag in tags %}
<option value="{{ one_tag.id }}">{{ one_tag.name }}</option>
{% endfor %}
</select>
</div>
<div class="col-md-8 col-sm-7">
<label for="news-select" style="display: none;"></label>
<select name="news" class="form-control input-md" id="news-select">
<option value="0">--请选择文章--</option>
</select>
</div>
</div>
<div class="form-group">
<label for="priority" class="col-md-2 col-sm-2 control-label">选择优先级</label>
<div class="col-md-2 col-sm-3">
<select name="priority" id="priority" class="form-control input-md">
<option value="0">--请选择优先级--</option>
{% for id, value in priority_dict.items %}
<option value="{{ id }}">{{ value }}</option>
{% endfor %}
</select>
</div>
</div>
</div>
<div class="box-footer">
<a href="javascript:void(0);" class="btn btn-primary pull-right" id="save-btn">保存</a>
</div>
</div>
</div>
{% endblock %}
{% block script %}
<script src="/static/js/admin/news/news_hot_add.js"></script>
{% endblock %}
$(function () {
let $tagSelect = $("#category-select"); // 获取选择分类标签元素
let $newsSelect = $("#news-select"); // 获取选择文章标签元素
let $saveBtn = $('#save-btn'); // 获取保存按钮元素
// 选择文章不同类别,获取相应的文章
$tagSelect.change(function () {
// 获取当前选中的下拉框的value
let sTagId = $(this).val();
if (sTagId === '0') {
$newsSelect.children('option').remove();
$newsSelect.append(`<option value="0">--请选择文章--</option>`);
return
}
// 根据文章分类id向后端发起get请求
$.ajax({
url: "/admin/tags/" + sTagId + "/news/", // url尾部需要添加/
type: "GET",
dataType: "json",
})
.done(function (res) {
if (res.errno === "200") {
$newsSelect.children('option').remove();
$newsSelect.append(`<option value="0">--请选择文章--</option>`);
res.data.news.forEach(function (one_news) {
let content = `<option value="${one_news.id}">${one_news.title}</option>`;
$newsSelect.append(content)
});
} else {
// swal.showInputError(res.errmsg);
fAlert.alertErrorToast(res.errmsg);
}
})
.fail(function () {
message.showError('服务器超时,请重试!');
});
});
// 点击保存按钮执行的事件
$saveBtn.click(function () {
// 获取优先级
let priority = $("#priority").val();
// 获取下拉框中选中的文章标签id 和 文章id
let sTagId = $tagSelect.val();
let sNewsId = $newsSelect.val();
// 打印值
console.log(`
priority(优先级): ${priority}
tagId(文章标签id): ${sTagId}
newsId(文章id): ${sNewsId}
`);
// 判断是否为 0, 表示在第一个 未选择
if (sTagId !== '0' && sNewsId !== '0' && priority !== '0') {
let sDataParams = {
"priority": priority,
"news_id": sNewsId
};
$.ajax({
// 请求地址
url: "/admin/hotnews/add/", // url尾部需要添加/
// 请求方式
type: "POST",
data: JSON.stringify(sDataParams),
// 请求内容的数据类型(前端发给后端的格式)
contentType: "application/json; charset=utf-8",
// 响应数据的格式(后端返回给前端的格式)
dataType: "json",
})
.done(function (res) {
if (res.errno === "200") {
message.showSuccess("热门文章创建成功");
setTimeout(function () {
window.location.href = '/admin/hotnews/';
}, 800)
} else {
// swal.showInputError(res.errmsg);
message.showError(res.errmsg);
}
})
.fail(function () {
message.showError('服务器超时,请重试!');
});
} else {
message.showError("文章分类、文章以及优先级都要选!");
}
});
// get cookie using jQuery
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
let cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
let cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
// Setting the token on the AJAX request
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
});
网友评论