def release(): user = UserInfo.query.get(session['user_id']) category_list = NewsCategory.query.all() try: # 有带新闻参数的get方式请求,认为是修改新闻的请求 news_id = int(request.args.get('news_id')) news = NewsInfo.query.get(news_id) except: news = None if request.method == 'GET': # news为NewsInfo对象或者None,当为None时,模板中即不显示值 return render_template('news/user_news_release.html', category_list=category_list, news=news) elif request.method == 'POST': dict1 = request.form title = dict1.get('title') category_id = int(dict1.get('category')) summary = dict1.get('summary') context = dict1.get('content') try: __news_pic = request.files.get('news_pic') news_picname = pic1(__news_pic) except: # 用户没有上传图片,则存值空字符串 news_picname = '' if not all((title, category_id, summary, context)): # html中存在要用到news的html,错误信息回传时,也需要传news对象 return render_template('news/user_news_release.html', category_list=category_list, error_info='您的内容没有填写完整哦', news=news) try: if news: # 如果是修改操作,不用传用户id, news.update_time = datetime.now() else: news = NewsInfo() news.user_id = user.id # 如果获取到了上传的图片文件,就上传或者修改 if news_picname: news.pic = news_picname news.title = title news.category_id = category_id news.summary = summary news.status = 1 news.context = context db.session.add(news) db.session.commit() # 数据添加成功后默认去到新闻列表页 return redirect('/user/list') except: return render_template('news/user_news_release.html', category_list=category_list, error_info='服务器出错', news=news)
def release(): # 查询所有的分类,供编辑人员选择 category_list = NewsCategory.query.all() # 接收新闻的编号, 为了确认是创建还是修改 news_id = request.args.get('news_id') if request.method == 'GET': if news_id is None: # 展示页面 return render_template('news/user_news_release.html', category_list=category_list, news=None) else: # 如果有新闻编号存在,则进行修改操作,所以需要查询到原新闻并展示 news = NewsInfo.query.get(int(news_id)) return render_template('news/user_news_release.html', category_list=category_list, news=news) elif request.method == 'POST': # 新闻的添加处理 # 1.接收请求 dict1 = request.form title = dict1.get('title') category_id = dict1.get('category') summary = dict1.get('summary') content = dict1.get('content') # 接收新闻图片 news_pic = request.files.get('news_pic') if news_id is None: # 2.验证 if not all([title, category_id, summary, content, news_pic]): return render_template('news/user_news_release.html', category_list=category_list, msg='请将数据填写完整') else: if not all([title, category_id, summary, content]): return render_template('news/user_news_release.html', category_list=category_list, msg='请将数据填写完整') # 上传图片到七牛云, 修改文章内容的时候,默认不改图片,检查一下到底要不要改 if news_pic: from utils.qiniu_xjzx import upload_pic filename = upload_pic(news_pic) # 3.添加 if news_id is None: news = NewsInfo() else: news = NewsInfo.query.get(news_id) news.category_id = int(category_id) if news_pic: news.pic = filename news.title = title news.summary = summary news.content = content news.status = 1 news.update_time = datetime.now() news.user_id = session['user_id'] # 4.提交 db.session.add(news) db.session.commit() # 5.响应 return redirect('/user/newslist')