Views.py
from django.shortcuts import render
from markdown2 import Markdown
from . import util
from django import forms
import random
markdowner = Markdown()
class NewPage(forms.Form):
title = forms.CharField()
content = forms.CharField(widget=forms.Textarea)
def index(request):
return render(request, "encyclopedia/index.html", {
"entries": util.list_entries()
})
def title(request, title):
entry = util.list_entries()
if title in entry:
page = util.get_entry(title)
page_convert = markdowner.convert(page)
context = {"title": title, "page_display": page_convert}
return render(request, "encyclopedia/user_entry.html", context)
else:
return render(request, "encyclopedia/error.html",
{"message": "Sorry! The page that you searched was not found."})
def new_page(request):
if request.method == "POST":
form = NewPage(request.POST)
if form.is_valid():
title = form.cleaned_data["title"]
content = "#" + title + "\n" + form.cleaned_data["content"]
if title not in util.list_entries():
util.save_entry(title, content)
page = util.get_entry(title)
page_converted = markdowner.convert(page)
return render(request, "encyclopedia/user_entry.html", {"title": title, "page_display": page_converted})
else:
return render(request, "encyclopedia/error.html",
{"message": "A wikipedia entry already exists by this name."})
else:
return render(request, "encyclopedia/newpage.html", {"form": NewPage, "title": "New Page"})
def random_page(request):
if request.method == "GET":
entry = util.list_entries()
entry_count = len(util.list_entries())
random_no = random.randrange(0, entry_count - 1)
randompage = entry[random_no]
page = util.get_entry(randompage)
page_convert = markdowner.convert(page)
context = {"title": randompage, "page_display": page_convert}
return render(request, "encyclopedia/user_entry.html", context)