blog开发之后台管理
后台管理
主要功能:
1.文章的增删改查。
2.添加文章用到开源的kindediter编辑器。
页面效果:
视图代码
@login_required def cn_backend(request): article_list = models.Article.objects.filter(user=request.user).all() return render(request, 'blog/backend/backend.html', {'article_list': article_list}) @login_required def add_article(request): if request.method == 'POST': title = request.POST.get('title') content = request.POST.get('content') soup = BeautifulSoup(content, 'html.parser') desc = soup.text[0:150] + '...' models.Article.objects.create(title=title, content=content, desc=desc, user_id=request.user.pk) return redirect(reverse('blog:cn_backend')) return render(request, 'blog/backend/add_article.html') @login_required def upload(request): img_obj = request.FILES.get("upload_img") path = os.path.join(settings.MEDIA_ROOT, 'add_article_img', img_obj.name) with open(path, 'wb') as f: for line in img_obj: f.write(line) response = { 'error': 0, 'url': '/blog/media/add_article_img/%s' % img_obj.name } return JsonResponse(response) @login_required def edit_article(request, article_id): res = BaseResponse() article_obj = models.Article.objects.filter(pk=article_id).first() if not article_obj: res.code = 3001 res.error = '图书不存在!' return JsonResponse(res.dict) if article_obj.user.pk != request.user.pk: res.code = 3002 res.error = '非法操作' return JsonResponse(res.dict) if request.method == 'POST': title = request.POST.get("title") content = request.POST.get("content") # 防止xss攻击,过滤script标签 soup = BeautifulSoup(content, "html.parser") desc = soup.text[0:150] + "..." models.Article.objects.filter(pk=article_id).update(title=title, desc=desc, content=str(soup), user=request.user) return redirect(reverse('blog:cn_backend')) return render(request, 'blog/backend/change_article.html', {'article_obj': article_obj}) @login_required def del_article(request, article_id): res = BaseResponse() article_obj = models.Article.objects.filter(pk=article_id).first() if not article_obj: res.code = 3001 res.error = '图书不存在!' return JsonResponse(res.dict) if article_obj.user.pk != request.user.pk: res.code = 3002 res.error = '非法操作' return JsonResponse(res.dict) origin_url = reverse('blog:cn_backend') if request.method == 'GET': return render(request, 'blog/backend/delete.html', {'cancel': origin_url}) models.Article.objects.filter(pk=article_id).delete() return redirect(origin_url)
注意:
1.进入后台前需要登录,用Django自带的auth模块的装饰器login_required来实现。
2.添加文章,后台通过Bs4模块的BeautifulSoup来过滤非法字符串。
3.上转图片成功后,返回的字典要满足编辑器要求的格式。而且上传的文件夹要提前建立好。