def main(): content_list = [] files = os.listdir(data_path) for name in files: f = os.path.join(data_path, name) with open(f, 'r', encoding='utf-8') as f: content = f.read() item = (name[:-4], content[:100], content) content_list.append(item) # Article.objects.all().delete() for item in content_list: print('saving article: %s' % item[0]) article = Article() article.title = item[0] article.brief_content = item[1] article.content = item[2] article.save()
def add_article(request): if request.method == 'GET': col_list = Columns.objects.all() c_id = request.GET.get('c_id') if c_id: return render(request, 'add-article.html', { 'col_list': col_list, 'c_id': c_id, 'flag': 1 }) else: return render(request, 'add-article.html', { 'col_list': col_list, 'flag': 1 }) if request.method == 'POST': title = request.POST.get('title') keywords = request.POST.get('keywords') describe = request.POST.get('describe') category_id = int(request.POST.get('category')) content = request.POST.get('content') state = request.POST.get('visibility') cover = request.FILES.get('titlepic') # user_id 登录后将数据存入session,使用中间件 user_id = request.user.id art = Article() art.title = title art.keyword = keywords art.describe = describe art.col_id = category_id art.content = content art.state = state art.title_img = cover art.user_id = user_id art.save() for t in request.POST.get('tags').split(','): if Label.objects.filter(name=t).first(): art.lab.add(Label.objects.filter(name=t).first()) # 给文章添加标签 else: Label.objects.create(name=t) art.lab.add(Label.objects.filter(name=t).first()) # 给文章添加标签 return HttpResponseRedirect(reverse('myblog:article'))
def write(request): id = request.POST.get('id') title = request.POST.get('title') desc = request.POST.get('desc') author = request.session.get('username', None) content = request.POST.get('content') wordcount = request.POST.get('words') updatetime = datetime.now() username = request.session.get('username', None) user = User.objects.get(username=username) if id: article = Article.objects.get(id=id) else: article = Article() article.createtime = datetime.now() article.user = user article.title = title article.desc = desc article.author = author article.content = content article.wordcount = wordcount article.updatetime = updatetime # 添加字数 user.words = user.words + wordcount result = {} try: article.save() user.save() result['status'] = 200 except Exception: result['status'] = 500 return HttpResponse(json.dumps(result), content_type="application/json")