Commit 49e5cb4c by liuyingying

添加注释

parent 2b6e2ce0
......@@ -49,13 +49,15 @@ class Publications(models.Model):
isOpen = models.CharField(max_length=5, default='1')
editDateTime = models.DateField(default=timezone.now)
# *Pubs vs *Users
class PubToUser(models.Model):
pubID = models.BigIntegerField()
username = models.CharField(max_length=50)
userID = models.IntegerField(default=0)
#publish=0 用户私有,publish=1 组内可见,publish=2 公开
# publish=0 用户私有,publish=1 组内可见,publish=2 公开
class Articles(models.Model):
articleID = models.BigIntegerField(primary_key=True)
authorID = models.IntegerField()
......
......@@ -73,10 +73,8 @@
<span>MY-CVE</span>
<div class="content">
<div class="ul_list">
{% for year, cves in cve_year_list.items %}
{% if cves %}
<ul>
{% for cve in cves %}
{% for cve in cve_list %}
<li>
<span ><a href="{{ cve.url }}" target="_blank">{{ cve.identifier }}</a></span>
<span >{{ cve.software }}</span>
......@@ -84,8 +82,6 @@
</li>
{% endfor %}
</ul>
{% endif %}
{% endfor %}
</div>
</div>
</div>
......
......@@ -95,18 +95,14 @@
<span>{{ it.date }}</span>
{% if key == 'publication' %}
<span>{{ it.author }}&nbsp;在{{ it.journalname }}上发表了{{ it.publishType }}</span>
<span><a target="_blank" href="{{ it.url }}">《{{ it.title }}》</a></span>
{% else %}
{% if key == 'cve' %}
<span>{{ it.author }}&nbsp;提交了&nbsp;</span>
<span><a target="_blank" href="{{ it.url }}">{{ it.title }}</a></span>
{% else %}
<span>{{ it.author }}&nbsp;写了文章</span>
<span><a target="_blank" href="{{ it.url }}">《{{ it.title }}》</a></span>
{% endif %}
{% endif %}
<span><a target="_blank" href="{{ it.url }}">《{{ it.title }}》</a></span>
</div>
{% endfor %}
......
......@@ -144,7 +144,7 @@
<div class="add_one">
<button class="add_url" onclick="addArt()" title="添加外部平台文章链接"></button>
<a href="{% url 'hunter:write_art' %}" title="写文章">
<a href="{% url 'hunter:write_art_html' %}" title="写文章">
<svg t="1587711451871" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2741" width="20" height="20"><path d="M863.079412 351.09129a29.2569 29.2569 0 0 1 58.5138 0v555.881108a117.027602 117.027602 0 0 1-117.027601 117.027602H219.427602a117.027602 117.027602 0 0 1-117.027602-117.027602V146.292987a117.027602 117.027602 0 0 1 117.027602-117.027602h380.339706a29.2569 29.2569 0 0 1 0 58.513801H219.427602a58.513801 58.513801 0 0 0-58.513801 58.513801v760.679411a58.513801 58.513801 0 0 0 58.513801 58.513801h585.138009a58.513801 58.513801 0 0 0 58.513801-58.513801V351.09129zM855.414104 10.306913a29.2569 29.2569 0 1 1 44.587516 37.916943l-248.683654 292.569005a29.2569 29.2569 0 1 1-44.587516-37.916943l248.683654-292.569005zM307.198303 526.632692h263.312104a29.2569 29.2569 0 0 1 0 58.513801H307.198303a29.2569 29.2569 0 0 1 0-58.513801z m0 175.541403h409.596606a29.2569 29.2569 0 0 1 0 58.513801H307.198303a29.2569 29.2569 0 0 1 0-58.513801z" p-id="2742" fill="#6e829e"></path></svg>
</a>
</div>
......
......@@ -123,7 +123,7 @@
formdata.append("title",title);
formdata.append("content",content);
$.ajax({
url:'/write/',
url:'/save/article/',
type:'post',
data:formdata,
processData : false, // 使数据不做处理
......
......@@ -17,12 +17,13 @@ urlpatterns = [
path('user/detail/<int:user_id>/', views.resume_html, name='resume'),
#新建文章页面
path('write/', views.write_art_html, name='write_art'),
path('write/', views.write_art_html, name='write_art_html'),
#查看文章页面
path('article/<int:article_id>/', views.article_html, name='article'),
#编辑文章页面
path('edit/article/<int:article_id>/', views.edit_art_html, name='edit_art'),
#api
path('save/article/', views.save_article, name='save_article'),
path('save/edit/article/', views.save_edit_art, name='save_edit_art'),
path('uploadImg/', views.uploadImg, name='uploadImg'),
path('add/article/url/', views.add_url_article, name='add_url_article'),
......@@ -39,12 +40,10 @@ urlpatterns = [
path('edit/publication/', views.edit_publication, name='edit_publication'),
path('add/cve/', views.add_cve, name='add_cve'),
path('edit/cve/', views.edit_cve, name='edit_cve'),
path('add/article/', views.add_article, name='add_article'),
path('ht/admin/', views.admin, name='admin'),
path('operator/', views.operator, name='operator'),
path('add_user/', views.add_user, name='add_user'),
path('update_article/', views.update_article, name='update_article'),
path('add_sub_score/', views.add_sub_score, name='add_sub_score'),
path('get_user_scores/', views.user_score_records, name='get_user_scores'),
......
......@@ -18,10 +18,10 @@ from django.db.models import Count
from django.views.decorators.csrf import ensure_csrf_cookie
# 登录
def login(request):
username = request.POST['username']
password = request.POST['password']
user_id=""
try:
db_info = User.objects.get(name=username)
except ObjectDoesNotExist as e:
......@@ -31,12 +31,14 @@ def login(request):
if db_info.pwd == password:
user_id = db_info.userID
request.session['user_id'] = user_id
# 登录成功返回用户id
response = JsonResponse({"message": "success", "userid": user_id})
else:
response = JsonResponse({"message": "密码错误"})
return response
# 退出登录
def logout(request):
print('call logout')
request.session['user_id'] = None
......@@ -44,7 +46,7 @@ def logout(request):
return response
# 提交个人信息
def profile_submit(request):
userID=request.POST["userID"]
name_hanzi=request.POST["name_hanzi"]
......@@ -56,7 +58,8 @@ def profile_submit(request):
profile = request.POST['profile']
print(profile)
edus = {}
if int(length)>0:
# 如果提交了教育经历
if int(length) > 0:
edu_arr = request.POST['edu_arr']
print(edu_arr)
edu_arr = edu_arr.split('#')
......@@ -71,22 +74,73 @@ def profile_submit(request):
except ProgrammingError as e:
return JsonResponse({"message": 0, 'error': e})
print(edus)
# 如果提交了密码
if len(str(pwd).strip()) > 0:
try:
User.objects.filter(userID=userID).update(name_hanzi=name_hanzi, name_eng=name_eng, pwd=pwd, mailAddress= mail, personal_website=website, profile=profile)
return JsonResponse({'message':1})
except ObjectDoesNotExist as e:
return JsonResponse({"message":0,'error':e})
return JsonResponse({"message": 0, 'error': e})
else:
try:
User.objects.filter(userID=userID).update(name_hanzi=name_hanzi, name_eng=name_eng, mailAddress= mail, personal_website=website, profile=profile)
return JsonResponse({'message':1})
except ObjectDoesNotExist as e:
return JsonResponse({"message":0,'error':e})
return JsonResponse({"message": 0, 'error': e})
def save_article(request):
userID = request.POST.get('userID', '')
title = request.POST.get('title', '')
content = request.POST.get('content', '')
editdatetime = datetime.datetime.now().date()
is_have_file = request.POST['isHaveFile']
link = ""
# 加入判断题目是否已存在
is_have = Articles.objects.filter(title=title).count()
if is_have > 0:
return JsonResponse({'message': 0, 'error': '该题目已存在'})
# 是否上传附件
if int(is_have_file) > 0:
myfile = request.FILES['myfile']
if Articles.objects.filter(attachment=myfile.name).count():
return JsonResponse({'message': 0, 'error': '文件已存在'})
else:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
destination = os.path.join(BASE_DIR, 'hunter', 'static', 'hunter/articles', myfile.name)
if os.path.exists(destination):
os.remove(destination)
with open(destination, 'wb+') as dest:
for chunk in myfile.chunks():
dest.write(chunk)
dest.close()
link = myfile.name
# 写入数据库
if Articles.objects.last() is None:
articleID = 1
else:
articleID = Articles.objects.last().articleID + 1
# 判断作者是否存在
try:
authorID = User.objects.get(userID=userID)
except ObjectDoesNotExist as e:
response = JsonResponse({"message": 0, 'error': '用户不存在,请检查是否登录'})
return response
# 将文章写入数据库
try:
Articles.objects.create(articleID=articleID, authorID=userID, title=title, content=content,
editDateTime=editdatetime,
attachment=link)
response = JsonResponse({"message": 1})
except ProgrammingError as e:
response = JsonResponse({"message": 0, 'error': '数据库错误'})
return response
return response
# 保存修改后的文章
def save_edit_art(request):
userID = request.POST.get('userID', '')
title = request.POST.get('title', '')
......@@ -94,7 +148,8 @@ def save_edit_art(request):
editdatetime = datetime.datetime.now().date()
is_have_file = request.POST['isHaveFile']
articleID = request.POST.get('articleID')
link=""
link = ""
# 验证文章存在& 当前编辑用户与文章作者一致
try:
a = Articles.objects.get(articleID=articleID)
authorID = a.authorID
......@@ -106,6 +161,7 @@ def save_edit_art(request):
except ObjectDoesNotExist as e:
response = JsonResponse({"message": 0, 'error': '文章不存在,请检查链接'})
return response
# 是否有上传附件
if int(is_have_file) > 0:
myfile = request.FILES['myfile']
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
......@@ -137,7 +193,7 @@ def save_edit_art(request):
return response
# 添加文章链接
def add_url_article(request):
userID = request.POST.get('userID', '')
title = request.POST.get('title', '')
......@@ -162,6 +218,7 @@ def add_url_article(request):
return response
# 删除发表刊物
def delete_publication(request):
pub_id = request.POST['pub_id']
print(pub_id)
......@@ -175,7 +232,7 @@ def delete_publication(request):
return response
# 删除CVE
def delete_cve(request):
cve_id = request.POST['cve_id']
try:
......@@ -187,7 +244,7 @@ def delete_cve(request):
return response
# 删除文章
def delete_article(request):
article_id = request.POST['article_id']
try:
......@@ -199,7 +256,7 @@ def delete_article(request):
return response
# 更改刊物公开状态
def change_pub_status(request):
pubID = request.POST['pubID']
isOpen = request.POST['isOpen']
......@@ -211,22 +268,21 @@ def change_pub_status(request):
return JsonResponse({'message':0,'error':e})
# 添加发表刊物
def add_publication(request):
title = request.POST['title']
print(title)
authors = request.POST['authors']
uploadby = request.POST['username']
publishType = request.POST['type']
myfile = request.FILES['myfile']
print(authors)
# 替换不规范中文逗号
s=','
authors = authors.replace(s, ',')
print(authors)
journalname = request.POST.get('journalname')
date = request.POST.get('date')
print(date)
index = request.POST.get('index')
isPublish=request.POST['isPublish']
# 论文题目是否冲突
if Publications.objects.filter(title=title).count() > 0:
return JsonResponse({'message': 0, "error": "该标题已存在"})
if Publications.objects.last() is None:
......@@ -247,33 +303,31 @@ def add_publication(request):
except ProgrammingError as e:
return JsonResponse({"message": 0})
authorArr = authors.split(',')
print(authorArr)
# 依次将作者保存至PubToUser数据库表中
for author in authorArr:
users_list = User.objects.all().values('name')
user_list=[]
for user in users_list:
user_list.append(user['name'])
author = str(author).lower().strip()
# 作者名称可能的格式:Liu Yingying & Yingying Liu & liuyingying
# 进行格式转换,将属于网站成员的作者在保存记录同时记录 userID
# 非网站成员没有userID
if ' ' in author:
author_version1 = author.replace(' ','')
author_version1 = author.replace(' ', '')
author_version2 = author.split(' ')[1]+str(author).lower().strip().split(' ')[0]
else:
author_version1 = author.replace(' ', '')
author_version2 = author
print(user_list)
print(author_version1)
print(author_version2)
if author_version1 in user_list:
userID = User.objects.filter(name=author_version1).values('userID')[0]['userID']
try:
print("测试:LIU Yingying")
PubToUser.objects.create(pubID = pubID,username=author, userID=userID)
response = JsonResponse({"message": 1, 'pubID':pubID})
except ProgrammingError as e:
return JsonResponse({"message": 0})
else:
if author_version2 in user_list:
print("测试:Yingying LIU")
userID = User.objects.filter(name=author_version2).values('userID')[0]['userID']
try:
PubToUser.objects.create(pubID = pubID,username=author, userID=userID)
......@@ -286,12 +340,10 @@ def add_publication(request):
response = JsonResponse({"message": 1, 'pubID':pubID})
except ProgrammingError as e:
return JsonResponse({"message": 0})
# message["warning"] = "上传成功"
# return HttpResponse(json.dumps(message), content_type='application/json')
return response
# 修改发表刊物(论文、期刊)
def edit_publication(request):
pubID = request.POST['pubID']
title = request.POST['title']
......@@ -299,15 +351,18 @@ def edit_publication(request):
uploadby = request.POST['username']
publishType = request.POST['type']
isHaveFile = request.POST['isHaveFile']
s=','
# 如果存在中文逗号,则统一替换为英文逗号
s = ','
authors = authors.replace(s, ',')
journalname = request.POST.get('journalname')
date = request.POST.get('date')
index = request.POST.get('index')
isPublish=request.POST['isPublish']
isPublish = request.POST['isPublish']
origin_author = Publications.objects.get(pubID=pubID).authors
if Publications.objects.filter(pubID=pubID).count() <=0:
return JsonResponse({'message': 0, "error": "该出版不存在"})
# 是否重新上传了文件?是则覆盖
if isHaveFile == '1':
myfile = request.FILES['myfile']
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
......@@ -334,11 +389,12 @@ def edit_publication(request):
response = JsonResponse({"message": 1, 'pubID': pubID})
except ProgrammingError as e:
return JsonResponse({"message": 0})
# 判断是否修改了作者
authorArr = authors.split(',')
originArr = origin_author.split(',')
# 是:删除旧的论文-作者记录,创建新纪录
if authorArr != originArr:
print(authorArr)
print(originArr)
PubToUser.objects.filter(pubID=pubID).delete()
for author in authorArr:
users_list = User.objects.all().values('name')
......@@ -346,15 +402,13 @@ def edit_publication(request):
for user in users_list:
user_list.append(user['name'])
author = str(author).lower().strip()
# 将用户提交的名字格式进行转换、判断 等操作
if ' ' in author:
author_version1 = author.replace(' ', '')
author_version2 = author.split(' ')[1] + str(author).lower().strip().split(' ')[0]
else:
author_version1 = author.replace(' ', '')
author_version2 = author
print(user_list)
print(author_version1)
print(author_version2)
if author_version1 in user_list:
userID = User.objects.filter(name=author_version1).values('userID')[0]['userID']
try:
......@@ -379,6 +433,7 @@ def edit_publication(request):
return response
# 添加CVE
def add_cve(request):
owner = request.POST['owner']
bugType = request.POST['bugType']
......@@ -398,7 +453,7 @@ def add_cve(request):
return response
# 修改CVE
def edit_cve(request):
bugType = request.POST['bugType']
identifier = request.POST['cve_id']
......@@ -415,19 +470,62 @@ def edit_cve(request):
return response
# 修改文章的公开状态
def update_article(request):
art_id = request.POST['art_id']
print('update_article, art_id = ', art_id)
art = Articles.objects.get(articleID=int(art_id))
print(art)
art_pub = request.POST.get('publish')
if art_pub != None:
if art_pub is not None:
art.publish = art_pub
art.save()
return JsonResponse({"message": "success"})
return JsonResponse({"message": "failed"})
def add_article(request):
return 0
\ No newline at end of file
# 加减积分
def add_sub_score(request):
if request.is_ajax():
action = request.POST.get("action")
username = request.POST.get('username')
if User.objects.filter(name=username):
userID= request.POST.get('userID')
user_score = User.objects.get(name=username).score
scoreUsed = User.objects.get(name=username).scoreUsed
reason_to_add = request.POST.get("reason")
add_num = request.POST.get("score")
score = 0
totalNum=int(user_score)
# 加分
if action == '1':
totalNum += int(add_num)
score = int(add_num)
# 减分
if action == '0':
totalNum -= int(add_num)
scoreUsed = scoreUsed + int(add_num)
score = -int(add_num)
if ScoreRecords.objects.last() is None:
recordID = 1
else:
recordID = ScoreRecords.objects.last().recordID+1
try:
ScoreRecords.objects.create(recordID=recordID,username=username,userID=userID,
reason = reason_to_add,
editDate=datetime.datetime.now().date(),
score=score)
except EOFError as e:
response = JsonResponse({"message": e})
try:
User.objects.filter(name=username).update(score=totalNum, scoreUsed=scoreUsed)
response = JsonResponse({"message": "success"})
return response
except EOFError as e:
response = JsonResponse({"message": e})
return response
else:
response = JsonResponse({"message":"用户不存在"})
return response
\ No newline at end of file
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404, HttpResponseNotFound
from django.http import HttpResponse, HttpResponseNotFound
from ..models import *
from django.core.exceptions import ObjectDoesNotExist
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.template.context_processors import csrf
import os
from django.db.utils import ProgrammingError
import datetime
from operator import itemgetter, attrgetter
from django.shortcuts import redirect
from operator import attrgetter
from django.core.exceptions import ValidationError
import json
from django.views import generic
from django.db.models.aggregates import Count
from django.db.models import Count
from django.views.decorators.csrf import ensure_csrf_cookie
import os
import datetime
# Create your views here.
# 首页
......@@ -24,6 +19,7 @@ def index_html(request):
print("request index.html, user_id = ", user_id)
user_list = User.objects.filter(isCurrent=1).all()
user_type_list = {"Academic STAFF": [], "Phd": [], "Master": [], "Engineer STAFF": []}
# 获取现成员并分类
for u in user_list:
if u.member_type == 0:
u.member_type = "Academic STAFF"
......@@ -35,7 +31,7 @@ def index_html(request):
u.member_type = "Phd"
member_type = u.member_type
user_type_list[member_type].append(u)
# 获取前成员并分类
user_list_former = User.objects.filter(isCurrent=0, identity='0').all()
user_type_list_former = {"Academic STAFF": [], "Phd": [], "Master": [], "Engineer STAFF": []}
for u in user_list_former:
......@@ -51,50 +47,43 @@ def index_html(request):
u.member_type = "Phd"
member_type = u.member_type
user_type_list_former[member_type].append(u)
# 获取发表文章并排序
publication_list = Publications.objects.filter(isOpen='1').order_by('-date')
publication_year_list = {}
for pub in publication_list:
year = str(pub.date)[0:4]
pub.date = str(pub.date)[5:10]
pub.link = pub.link.split('/')[-1]
print(pub.link)
# 根据年份分类
if year in publication_year_list.keys():
publication_year_list[year].append(pub)
else:
publication_year_list[year] = [pub]
# CVE
bug_list = Bugs.objects.all().order_by('-identifier')
cve_year_list = {}
# for cve in bug_list:
# year = str(cve.datetime)[0:4]
# cve.datetime = str(cve.datetime)[5:10]
# print(cve.datetime)
# if year in cve_year_list.keys():
# cve_year_list[year].append(cve)
# else:
# cve_year_list[year] = [cve]
article_list = Articles.objects.order_by('-editDateTime')
article_year_list = {}
for art in article_list:
#print(art.title, art.publish)
pub_type = int(art.publish)
if pub_type == 0: #article is private
# article is private
if pub_type == 0:
continue
elif pub_type == 1 and user_id == None: #internal article
# internal article
elif pub_type == 1 and user_id is None:
continue
year = str(art.editDateTime)[0:4]
art.editDateTime = str(art.editDateTime)[5:10]
u = User.objects.filter(userID=art.authorID).values('name')
art.authorID = u[0]['name']
# 根据年份分类
if year in article_year_list.keys():
article_year_list[year].append(art)
else:
article_year_list[year] = [art]
newest_post_list = {}
# 读取最近7天内动态
start = datetime.datetime.now().date()-datetime.timedelta(hours=23*7, minutes=59, seconds=59)
newest_publication = Publications.objects.filter(date__gte=start, isOpen='1').order_by('-editDateTime')
for pub in newest_publication:
......@@ -121,7 +110,6 @@ def index_html(request):
'user_type_list': user_type_list,
'user_type_list_former': user_type_list_former,
'publication_year_list': publication_year_list,
'cve_year_list': cve_year_list,
'cve_list': bug_list,
'article_year_list': article_year_list,
'newest_post_list': newest_post_list,
......@@ -134,14 +122,11 @@ def user_html(request, user_id):
usr = get_object_or_404(User, pk=user_id)
print(usr.name)
username = usr.name
u = {'userID': user_id, 'name': username}
my_publication_year_list = {}
pub_ids = PubToUser.objects.filter(userID=user_id).all().values('pubID')
print("user_html publications: ")
for pub_id in pub_ids:
#print(pub_id, )
pub = get_object_or_404(Publications, pk=pub_id['pubID'])
print(pub.pubID, pub.title)
year = str(pub.date)[0:4]
pub.date = str(pub.date)[5:10]
pub.link = pub.link.split('/')[-1]
......@@ -155,9 +140,6 @@ def user_html(request, user_id):
for k in sorted(my_publication_year_list, reverse=True):
publication_year_list[k] = my_publication_year_list[k]
print(publication_year_list)
print(my_publication_year_list)
my_article_list = Articles.objects.filter(authorID=user_id).order_by('-editDateTime')
my_article_year_list = {}
for art in my_article_list:
......@@ -168,27 +150,18 @@ def user_html(request, user_id):
my_article_year_list[year].append(art)
else:
my_article_year_list[year] = [art]
# 根据年份分类
my_bug_list = Bugs.objects.filter(owner=username).order_by('-identifier')
my_cve_year_list = {}
for cve in my_bug_list:
year = str(cve.datetime)[0:4]
cve.datetime = str(cve.datetime)[5:10]
print(cve.datetime)
if year in my_cve_year_list.keys():
my_cve_year_list[year].append(cve)
else:
my_cve_year_list[year] = [cve]
context = {
'user': usr,
'publication_year_list': publication_year_list,
'cve_year_list': my_cve_year_list,
'cve_list': my_bug_list,
'article_year_list': my_article_year_list,
}
print("display user: ", usr)
return render(request, 'user.html', context)
# 个人简历 (resume or CV)
def resume_html(request, user_id):
usr = get_object_or_404(User, pk=user_id)
......@@ -212,14 +185,6 @@ def resume_html(request, user_id):
publication_year_list[k] = my_publication_year_list[k]
my_bug_list = Bugs.objects.filter(owner=username).order_by('-datetime')
my_cve_year_list = {}
for cve in my_bug_list:
year = str(cve.datetime)[0:4]
cve.datetime = str(cve.datetime)[5:10]
if year in my_cve_year_list.keys():
my_cve_year_list[year].append(cve)
else:
my_cve_year_list[year] = [cve]
my_article_list = Articles.objects.filter(authorID=user_id).order_by('-editDateTime')
my_article_year_list = {}
......@@ -233,17 +198,18 @@ def resume_html(request, user_id):
my_article_year_list[year] = [art]
education_list = Education.objects.filter(userID=user_id).order_by("-start")
for item in education_list:
item.start = str(item.start)[0:10].replace('-','.')
item.stop = str(item.stop)[0:10].replace('-','.')
item.start = str(item.start)[0:10].replace('-', '.')
item.stop = str(item.stop)[0:10].replace('-', '.')
context = {
'user': usr,
'art_year_list': my_article_year_list,
'publication_year_list': publication_year_list,
'cve_year_list': my_cve_year_list,
'cve_list': my_bug_list,
'education_list': education_list,
}
return render(request, 'detail.html', context)
# 文章展示页面
def article_html(request, article_id):
art = get_object_or_404(Articles, pk=article_id)
......@@ -252,7 +218,7 @@ def article_html(request, article_id):
return render(request, 'article.html', {'article': art})
# 新建文章页面
# 文章页面
def write_art_html(request):
if request.is_ajax():
userID = request.POST.get('userID', '')
......@@ -260,7 +226,7 @@ def write_art_html(request):
content = request.POST.get('content', '')
editdatetime = datetime.datetime.now().date()
is_have_file = request.POST['isHaveFile']
link=""
link = ""
# 加入判断题目是否相同
is_have = Articles.objects.filter(title=title).count()
if is_have > 0:
......@@ -271,7 +237,7 @@ def write_art_html(request):
return JsonResponse({'message': 0, 'error': '文件已存在'})
else:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
destination = os.path.join(BASE_DIR, 'hunter', 'static', 'articles', myfile.name)
destination = os.path.join(BASE_DIR, 'hunter', 'static', 'hunter/articles', myfile.name)
if os.path.exists(destination):
os.remove(destination)
with open(destination, 'wb+') as dest:
......@@ -286,7 +252,7 @@ def write_art_html(request):
try:
authorID = User.objects.get(userID=userID)
except ObjectDoesNotExist as e:
response = JsonResponse({"message": 0, 'error':'用户不存在,请检查是否登录'})
response = JsonResponse({"message": 0, 'error': '用户不存在,请检查是否登录'})
return response
try:
Articles.objects.create(articleID=articleID, authorID=userID, title=title, content=content,
......@@ -295,27 +261,31 @@ def write_art_html(request):
response = JsonResponse({"message": 1})
except ProgrammingError as e:
response = JsonResponse({"message": 0, 'error': '数据库错误'})
return response
return response
return render(request, 'write.html')
#编辑文章页面
# 编辑文章页面
def edit_art_html(request, article_id):
art = get_object_or_404(Articles, pk=article_id)
return render(request, 'editArticle.html', {'article': art})
# 【上传】写文章时插入的图片
@csrf_exempt
def uploadImg(request):
file_obj = request.FILES.get("image")
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
file_path = os.path.join(BASE_DIR, 'hunter', 'static', 'articles/images', file_obj.name)
link_path = os.path.join('/static', 'articles/images', file_obj.name)
with open(file_path,'wb') as f:
with open(file_path, 'wb') as f:
for chunk in file_obj.chunks():
f.write(chunk)
return HttpResponse(link_path)
# 编辑个人信息
def profile_edit(request, user_id):
user = get_object_or_404(User, pk=user_id)
edu = Education.objects.filter(userID=user_id).order_by("-start")
......@@ -325,29 +295,29 @@ def profile_edit(request, user_id):
return render(request, 'profile.html', {'user': user, 'edus':edu})
# 检查管理员权限
def check_admin_privilage(user_id):
try:
user_id = int(user_id)
except:
except ObjectDoesNotExist:
return False
user = User.objects.get(userID = user_id)
if user != None or user.is_admin():
user = User.objects.get(userID=user_id)
if user is not None or user.is_admin():
return True
else:
return False
# 管理员
def admin(request):
admin_id = request.session.get('admin_id')
if admin_id == None:
if admin_id is None:
if request.method != 'POST':
return HttpResponseNotFound('<h1>Page not found</h1>')
user_id = request.POST.get('user_id', '')
if user_id == '':
return HttpResponse(status=404)
print ("admin user_id = ", user_id)
return HttpResponse(status=404)
if not check_admin_privilage(user_id):
return HttpResponse(status=404)
......@@ -373,24 +343,29 @@ def admin(request):
records = []
else:
records = ScoreRecords.objects.all()
print(users)
return render(request,"admin.html", locals())
# 读取用户积分记录
def user_score_records(request):
user_id = None
if request.method == 'POST':
user_id = request.POST.get('user_id')
if user_id == None:
if user_id is None:
user_id = request.session.get('user_id')
if user_id != None:
if user_id is not None:
records = ScoreRecords.objects.filter(userID = user_id);
return render(request,"user_score.html", locals())
# 管理员的操作
def operator(request):
message = {}
print("cal api operator.")
if request.is_ajax():
# 判断操作类型
actiontype = request.POST.get('actiontype')
# 创建用户
if actiontype == '0':
username = request.POST.get('username')
password = request.POST.get('password')
......@@ -407,7 +382,7 @@ def operator(request):
userID = User.objects.last().userID + 1
try:
userAdd=User.objects.create(userID=userID, name=username, pwd=password)
message["warning"]="添加成功"
message["warning"] = "添加成功"
users = User.objects.all()
userList = []
for user in users:
......@@ -417,6 +392,7 @@ def operator(request):
except ValidationError as e:
message["warning"]=e;
return HttpResponse(json.dumps(message), content_type='application/json')
# 删除用户
if actiontype == '1':
delname = request.POST.get('delname')
try:
......@@ -432,6 +408,7 @@ def operator(request):
except:
message["warning"]="删除出错"
return HttpResponse(json.dumps(message), content_type='application/json')
# 重置用户密码
if actiontype == '2':
resetPwd = request.POST.get('resetPwd')
resetname = request.POST.get('resetname')
......@@ -442,22 +419,23 @@ def operator(request):
except:
message["warning"]="密码更新错误"
return HttpResponse(json.dumps(message), content_type='application/json')
# 更改用户权限
if actiontype == '3':
identity = request.POST.get('identity')
username = request.POST.get('username')
try:
User.objects.filter(name=username).update(identity=identity)
message["flag"]="1";
message["warning"]="权限更改成功"
message["flag"] = "1"
message["warning"] = "权限更改成功"
return HttpResponse(json.dumps(message), content_type='application/json')
except:
message["warning"]="权限更改错误"
message["flag"]="1";
except ObjectDoesNotExist:
message["warning"] = "权限更改错误"
message["flag"] = "1"
return HttpResponse(json.dumps(message), content_type='application/json')
# 删除发表刊物
if actiontype == '4':
pubtitle = request.POST.get('delpub')
pubFileName = request.POST.get('pubFileName')
print (pubtitle)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
destination = os.path.join(BASE_DIR, 'hunter', 'static', 'publications', pubFileName)
try:
......@@ -469,87 +447,9 @@ def operator(request):
Publications.objects.filter(title=pubtitle).delete()
if os.path.exists(destination):
os.remove(destination)
message["warning"]="1"
return HttpResponse(json.dumps(message),content_type='application/json')
except:
message["warning"]="2"
return HttpResponse(json.dumps(message),content_type='application/json')
return render_to_response('admin.html', locals())
def add_user(request):
print('call api add_user')
if request.is_ajax():
username = request.POST.get('username')
password = request.POST.get('password')
message={}
if username == '' or password == '':
return render(request, 'admin.html', {'message': '用户名或密码不能为空'})
result = User.objects.filter(name=username)
if result:
return render(request, 'admin.html',{'message':'用户名已存在'})
if User.objects.last() is None:
userID = 1
else:
userID = User.objects.last().userID + 1
userAdd=User.objects.create(userID=userID, name=username, pwd=password)
if userAdd:
return render(request, 'admin.html',{'message':'添加成功'})
else:
return render(request, 'admin.html',{'message':'添加失败'})
return render(request, 'admin.html')
def add_sub_score(request):
if request.is_ajax():
action = request.POST.get("action")
# 加分
username = request.POST.get('username')
if User.objects.filter(name=username):
userID= request.POST.get('userID')
user_score = User.objects.get(name=username).score
scoreUsed = User.objects.get(name=username).scoreUsed
reason_to_add = request.POST.get("reason")
add_num = request.POST.get("score")
print (action)
score = 0
if action == '1':
totalNum = int(user_score) + int(add_num)
score = int(add_num)
if action == '0':
#totalNum = int(user_score)
scoreUsed = scoreUsed + int(add_num)
score = -int(add_num)
if ScoreRecords.objects.last() is None:
recordID = 1
else:
recordID = ScoreRecords.objects.last().recordID+1
try:
ScoreRecords.objects.create(recordID=recordID,username=username,userID=userID,
reason = reason_to_add,
editDate=datetime.datetime.now().date(),
score=score)
except EOFError as e:
response = JsonResponse({"message": e})
try:
User.objects.filter(name=username).update(score=totalNum,scoreUsed = scoreUsed)
response = JsonResponse({"message": "success"})
return response
except EOFError as e:
response = JsonResponse({"message": e})
return response
else:
response = JsonResponse({"message":"用户不存在"})
return render(request, 'admin.html')
def getUserScore(request):
if request.is_ajax():
if User.objects.filter(identity='0'):
users = User.objects.filter(identity='0')
for user in users:
user.curScore = user.score-user.scoreUsed
results = serializers.serialize("json", users)
return HttpResponse(results)
return render(request,'admin.html')
return render(request,'admin.html')
\ No newline at end of file
message["warning"] = "1"
return HttpResponse(json.dumps(message), content_type='application/json')
except ObjectDoesNotExist:
message["warning"] = "2"
return HttpResponse(json.dumps(message), content_type='application/json')
return render('admin.html', locals())
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment