from django.shortcuts import render, redirect from django.http import HttpResponse from django.template import Template from django.template import Context from django.contrib.auth import authenticate, login from django.contrib.auth.decorators import login_required from django.views.defaults import page_not_found import markdown from bs4 import BeautifulSoup from .models import Site, Page, Image _TEMPLATE = """
{{site_header | safe}} {{page_body | safe}} """ def handler404(request, exception, template_name="404.html"): page_names = ["home", "schedule", "thingstodo"] working_path = request.path.lower() if working_path and working_path[0] == "/": working_path = working_path[1:] if working_path and working_path[-1] == "/": working_path = working_path[:-1] if working_path in page_names: return redirect(working_path) return page_not_found(request, exception, template_name) def get_site_header(site): template = Template(site.header) context = Context({"site": site}) return template.render(context) def get_index_body(site): template = Template(site.index) context = Context({"site": site}) return template.render(context) def index(request): site = Site.objects.get(pk=1) template = Template(_TEMPLATE) context = Context({"site": site, "site_header" : get_site_header(site), "page_body" : get_index_body(site)}) soup = BeautifulSoup(template.render(context)) return HttpResponse(soup.prettify()) def login_view(request): token = request.POST["token"] user = authenticate(request, username="guest", password=token) if user is not None: login(request, user) return redirect("home") else: return redirect("index") @login_required(login_url="/") def home(request): return get_page("Home") def get_page_header(site: Site): pages = site.page_set.order_by("priority").filter(navigable=True) template = Template(site.page_header) context = Context({"pages" : pages}) return template.render(context) def get_page_body(site: Site, page: Page): header = get_page_header(site) body = f"