mdblog/markdownblog/blog/views.py
2022-06-18 12:18:44 +02:00

89 lines
3 KiB
Python

import os
import random
from django.contrib.auth.decorators import login_required
from django.db import IntegrityError
from django.http import HttpResponse
from django.shortcuts import render, redirect
from blog.factories import TopicFactory
from blog.models import Topic, Tag, Blogpost
from django.views.decorators.csrf import csrf_exempt
from markdownblog import settings
def viewblog(request) -> HttpResponse:
return render(request, 'blog/index.html', {"debug": settings.DEBUG})
@login_required
@csrf_exempt
def order(request):
if request.method == "POST":
root_id = int(request.POST['rootID']) if request.POST['rootID'] != 'root_list' else None
child_id = int(request.POST['childID'])
objtype = request.POST['relinkType']
if objtype == 'topic':
child_topic = Topic.objects.get(pk=child_id)
child_topic.rootTopic = Topic.objects.get(pk=root_id) if root_id is not None else None
child_topic.save()
elif objtype == 'post':
post = Blogpost.objects.get(pk=child_id)
post.topic = Topic.objects.get(pk=root_id) if root_id is not None else None
post.save()
context = {'roottopics': Topic.objects.all().filter(rootTopic=None), 'allposts': Blogpost.objects.all()}
return render(request, 'blog/order.html', context)
@login_required
def addpost(request) -> HttpResponse:
context = {'alltopics': Topic.objects.all().order_by('name').values(), 'markdown': ''}
if request.method == 'POST':
title = request.POST['title']
markdown = request.POST['markdown']
tags = []
if 'tags' in request.POST and request.POST['tags'] != '':
tags_str = request.POST['tags'].split(" ")
for tag in tags_str:
tags.append(Tag.objects.get_or_create(name=tag))
topicid = request.POST['topic']
topic = None if topicid == "No topic" else Topic.objects.get(pk=topicid)
try:
new_post = Blogpost.objects.create(title=title, topic=topic)
new_post.tags.set(tags)
except IntegrityError:
context = {'alltopics': Topic.objects.all().order_by('name').values(),
'error': 'Blogpost titles need to be unique. No post created.',
"markdown": markdown}
return render(request, 'blog/addpost.html', context)
filepath = os.path.join(os.environ.get("MD_FILE_PATH"), title + ".md")
with open(filepath, "w+") as mdfile:
mdfile.write(markdown)
mdfile.close()
context['error'] = "Post " + title + " created."
return render(request, 'blog/addpost.html', context)
@login_required
def createmocks(request, objtype, n) -> HttpResponse:
topics = TopicFactory.create_batch(n)
for topic in topics:
topic.save()
while len(topics) > 1:
child = random.choice(topics)
topics.remove(child)
child.rootTopic = random.choice(topics)
child.save()
print('Created ' + str(n) + ' mock topics.')
return redirect("index")