from django.http import JsonResponse from django.contrib.auth.decorators import login_required from .models import Article, Tag, ArticleClass, Draft @login_required(login_url='/account/login/') def post_article(request): if request.method == 'POST': data = request.POST article_class = ArticleClass.objects.filter(Name=data['class']) if article_class: new_article = Article() new_article.Publisher = request.user new_article.Title = data['title'] new_article.Content = data['content'] new_article.Cover = data['cover'] new_article.Class = article_class.get() new_article.Read = 0 new_article.Like = 0 new_article.save() for i in range(0, 100): try: tag_name = data['tag[' + str(i) + ']'] tag = Tag.objects.filter(Name=tag_name) if tag: new_article.Tag.add(tag.get()) else: new_article.Tag.create(Name=tag_name) except Exception as e: break new_article.save() res = { 'code': '402', 'message': 'Publish Successfully' } return JsonResponse(res) else: res = { 'code': '403', 'message': 'Invalid data' } return JsonResponse(res) else: # 请求方法错误,请使用POST res = { 'code': '401', 'message': 'Please Use POST' } return JsonResponse(res) def article_list(request): articles = Article.object.all() res = { 'code': '402', 'articles': [] } for article in articles: res[articles].append({ 'Id': article.ArticleId, 'Title': article.Title, 'Content': article.Content, 'Publisher': article.Publisher.username, 'Read': article.Read, 'Like': article.Like, 'Publish_Time': article.Publish_Time, 'Edit_Time': article.Edit_Time, }) return JsonResponse(res, safe=False) @login_required(login_url='/account/login/') def get_article_classes(request): aclasses = ArticleClass.objects.all() classes = [] for aclass in aclasses: classes.append(aclass.Name) res = { 'code': '402', 'classes': classes } return JsonResponse(res) @login_required(login_url='/account/login/') def get_article_tags(request): tags = [] for tag in Tag.objects.all(): tags.append(tag.Name) res = { 'code': '402', 'tags': tags } return JsonResponse(res) @login_required(login_url='/account/login/') def save_draft(request): if request.method == 'POST': data = request.POST draft = Draft.objects.filter(Title=data['title'], Poster=request.user) if draft: draft = draft.get() draft.Content = data['content'] draft.save() else: new_draft = Draft() new_draft.Title = data['title'] new_draft.Content = data['content'] new_draft.Poster = request.user new_draft.save() res = { 'code': '402', 'message': 'Saved Successfully' } return JsonResponse(res) else: # 请求方法错误,请使用POST res = { 'code': '401', 'message': 'Please Use POST' } return JsonResponse(res)