bot50 2020-08-16 17:41:41 +00:00
commit 4033aa17bb
42 changed files with 726 additions and 0 deletions

0
db.sqlite3 Normal file
View File

0
encyclopedia/__init__.py Normal file
View File

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

3
encyclopedia/admin.py Normal file
View File

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

5
encyclopedia/apps.py Normal file
View File

@ -0,0 +1,5 @@
from django.apps import AppConfig
class EncyclopediaConfig(AppConfig):
name = 'encyclopedia'

11
encyclopedia/markdown.py Normal file
View File

@ -0,0 +1,11 @@
import re
class MyMarkdown():
def add_tags(tag, word):
return "<%s>%s</%s>" % (tag, word, tag)
def heading(string):
if re.search("")
def convert(string):

View File

3
encyclopedia/models.py Normal file
View File

@ -0,0 +1,3 @@
from django.db import models
# Create your models here.

View File

@ -0,0 +1,44 @@
html, body {
max-width: 100px;
overflow: hidden;
max-height: 100vh;
}
body {
margin:0;
background-color: white;
}
code {
white-space: pre;
}
h1 {
margin-top: 0px;
padding-top: 20px;
}
textarea {
height: 90vh;
width: 80%;
}
.main {
padding: 10px;
}
.search {
width: 100%;
font-size: 15px;
line-height: 15px;
}
.sidebar {
background-color: #f0f0f0;
height: 100vh;
padding: 20px;
}
.sidebar h2 {
margin-top: 5px;
}

View File

@ -0,0 +1,28 @@
{% extends "encyclopedia/layout.html" %}
{% block title %}
Create New Page
{% endblock %}
{% block body %}
<form action = "{% url 'create' %}" method = "POST">
{% csrf_token %}
Title: {{ form.title }}
<br>
<br>
<br>
Content:
<br>
{{ form.textarea }}
<br>
<br>
<br>
<br>
<input class="btn btn-primary" style="margin-bottom: 15px;" type="submit" value="Submit">
</form>
{% endblock %}

View File

@ -0,0 +1,29 @@
{% extends "encyclopedia/layout.html" %}
{% block title %}
Edit Page
{% endblock %}
{% block body %}
<form action = "{% url 'editSubmit' %}" method = "POST">
{% csrf_token %}
<br>
<br>
Title: {{ form.title }}
<br>
<br>
<br>
Content:
<br>
{{ form.textarea }}
<br>
<br>
<br>
<br>
<input type = "hidden" name = "or_title" value = "{{ title }}">
<input class="btn btn-secondary" style="margin-top: -100px;" type="submit" value = "submit">
</form>
{% endblock %}

View File

@ -0,0 +1,11 @@
{% extends "encyclopedia/layout.html" %}
{% block title %}
Error
{% endblock %}
{% block body %}
<h1 style="text-align: center">{{ error_heading }}</h1>
<p style="text-align: center">{{ error_message }}</p>
{% endblock %}

View File

@ -0,0 +1,17 @@
{% extends "encyclopedia/layout.html" %}
{% block title %}
Encyclopedia
{% endblock %}
{% block body %}
<h1>All Pages</h1>
<ul>
{% for entry in entries %}
<li><a href=/wiki/{{entry}}>{{ entry }}</a></li>
{% endfor %}
</ul>
{% endblock %}

View File

@ -0,0 +1,38 @@
{% load static %}
<!DOCTYPE html>
<html lang="en" style = "overflow-x: hidden;">
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet">
</head>
<body>
<div class="row">
<div class="sidebar col-lg-2 col-md-3">
<h2>Wiki</h2>
<form action = "{% url 'index' %}" method = "POST">
{% csrf_token %}
<input class="search" type="text" name="q" placeholder="Search Encyclopedia" id = "search">
</form>
<div>
<a href="{% url 'index' %}">Home</a>
</div>
<div>
<a href="{% url 'create' %}">Create New Page</a>
</div>
<div>
<a href="{% url 'random' %}">Random Page</a>
</div>
{% block nav %}
{% endblock %}
</div>
<div class="main col-lg-10 col-md-9">
{% block body %}
{% endblock %}
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,17 @@
{% extends "encyclopedia/layout.html" %}
{% block title %}
Search
{% endblock %}
{% block body %}
<h1>Search Results for "{{ search }}" </h1>
<ul>
{% for entry in res %}
<li><a href=/wiki/{{entry}}>{{ entry }}</a></li>
{% endfor %}
</ul>
{% endblock %}

View File

@ -0,0 +1,19 @@
{% extends "encyclopedia/layout.html" %}
{% block title %}
{{title}}
{% endblock %}
{% block body %}
{% for message in messages %}
<div class="alert alert-success" role="alert" method = "GET" style = "width: 1100px;">
{{ message }}
</div>
{% endfor %}
<br>
{{ wiki_content| safe }}
<form action="{% url 'edit' title %}" method="GET">
<button class="btn btn-outline-secondary">Edit</button>
{% csrf_token %}
</form>
{% endblock %}

3
encyclopedia/tests.py Normal file
View File

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

14
encyclopedia/urls.py Normal file
View File

@ -0,0 +1,14 @@
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("wiki/<str:title>",views.page,name="page"),
path("wiki/<str:title>/edit", views.edit, name="edit"),
path("submit", views.editSubmit, name="editSubmit"),
path("create",views.create,name="create"),
path("error",views.error,name="error"),
path("random",views.randomPage,name = "random"),
path("search",views.index,name = "search")
]

37
encyclopedia/util.py Normal file
View File

@ -0,0 +1,37 @@
import re
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
def list_entries():
"""
Returns a list of all names of encyclopedia entries.
"""
_, filenames = default_storage.listdir("entries")
return list(sorted(re.sub(r"\.md$", "", filename)
for filename in filenames if filename.endswith(".md")))
def save_entry(title, content):
"""
Saves an encyclopedia entry, given its title and Markdown
content. If an existing entry with the same title already exists,
it is replaced.
"""
filename = f"entries/{title}.md"
if default_storage.exists(filename):
default_storage.delete(filename)
default_storage.save(filename, ContentFile(content))
def get_entry(title):
"""
Retrieves an encyclopedia entry by its title. If no such
entry exists, the function returns None.
"""
try:
f = default_storage.open(f"entries/{title}.md")
return f.read().decode("utf-8")
except FileNotFoundError:
return None

162
encyclopedia/views.py Normal file
View File

@ -0,0 +1,162 @@
from django.shortcuts import render
from markdown2 import Markdown
from . import util
from django import forms
import random
from django.contrib import messages
from django.core.files.storage import default_storage
class CreateForm(forms.Form):
"""
Creates a form for creating a new entry with title and content.
"""
title = forms.CharField(label="Title ",max_length = 30)
textarea = forms.CharField(widget=forms.Textarea(attrs={'rows': 5,'cols': 40,'style': 'height: 23.5em;'}),label = 'TextArea')
class EditForm(forms.Form):
"""
Edits an existing form for with title and content.
"""
title = forms.CharField(label="Title",max_length = 30)
textarea = forms.CharField(widget=forms.Textarea(attrs={'rows': 5,'cols': 40,'style': 'height: 23.5em;'}),label = 'TextArea')
def page(request,title):
"""
Displays the content of an entry given it's title.
"""
markdown = Markdown()
wiki_content= markdown.convert(util.get_entry(title))
return render(request,"encyclopedia/wiki.html",{
"title": title,
"wiki_content":wiki_content
})
def index(request):
"""
index page and obtaining search result.
"""
if request.method == "GET":
return render(request, "encyclopedia/index.html", {
"entries": util.list_entries()
})
elif request.method == "POST":
search = request.POST.get("q", "")
entries = util.list_entries()
if search in entries:
return page(request,search)
else:
res = [i for i in entries if search in i]
if not res:
return error(request,error_heading = "Search not found!")
else:
return render(request,"encyclopedia/search.html",{
'res':res,
'search': search
})
def create(request):
"""
Dislays the created form, obtains the details and adding it entries.
"""
if request.method == "POST":
form = CreateForm(request.POST)
if form.is_valid():
title = form.cleaned_data["title"]
content = form.cleaned_data["textarea"]
if title in util.list_entries():
return error(request, error_heading = "Already Page Exists",error_message = "Would you like to choose a different title?")
if content[0] == '#':
util.save_entry(title,content)
else:
content = "# " + title +"\n"+ content
util.save_entry(title,content)
messages.success(request,"Entry added successfully")
request.method = "GET"
return page(request,title)
else:
return render(request,"encyclopedia/create.html",{
"form": CreateForm()
})
def error(request,error_heading = "Page not found!",error_message = "Would you like to add a new page with this title?"):
"""
Dispays given heading and message on the error page
"""
return render(request,"encyclopedia/error.html",{
'error_heading':error_heading,
'error_message':error_message
})
def randomPage(request):
"""
Displays a random page from the given list of entries.
"""
entries = util.list_entries()
title = random.choice(entries)
return page(request,title)
def edit(request,title):
"""
Displays the edit form.
"""
return render(request,"encyclopedia/edit.html",
{
"form":EditForm(initial = {
"title": title,
"textarea": util.get_entry(title)
}),
"title":title
})
def editSubmit(request):
"""
Obtains the submitted edit form and returns to edited entry.
"""
if request.method == "POST":
title = request.POST.get("or_title", "")
form = EditForm(request.POST)
if form.is_valid():
content = form.cleaned_data["textarea"]
edit_title = form.cleaned_data["title"]
old_content = util.get_entry(title)
if edit_title == title and old_content == content:
messages.success(request,"No edits done")
elif edit_title == title and old_content != content:
util.save_entry(title,content)
messages.success(request,"Edits Successful")
elif edit_title != title:
entries = util.list_entries()
exclude_entries = [i for i in entries if i != title]
if edit_title in exclude_entries:
return error(request, error_heading = "Already Page Exists",error_message = "Would you like to choose a different title?")
else:
filename = f"entries/{edit_title}.md"
util.save_entry(edit_title, content)
messages.success(request,"Edit succesful")
request.method = "GET"
return page(request,edit_title)
else:
return render(request,"encyclopedia/edit.html",{
"form": EditForm()
})

3
entries/CSS.md Normal file
View File

@ -0,0 +1,3 @@
# CSS
CSS is a language that can be used to add style to an [HTML](/wiki/HTML) page.

3
entries/Django.md Normal file
View File

@ -0,0 +1,3 @@
# Django
Django is a web framework written using [Python](/wiki/Python) that allows for the design of web applications that generate [HTML](/wiki/HTML) dynamically.

25
entries/Git.md Normal file
View File

@ -0,0 +1,25 @@
# Git
Git is a version control tool that can be used to keep track of versions of a software project.
## GitHub
GitHub is an online service for hosting git repositories.

2
entries/Go.md Normal file
View File

@ -0,0 +1,2 @@
# Go
Go is a statically typed, compiled programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson.

53
entries/HTML.md Normal file
View File

@ -0,0 +1,53 @@
# HTML
HTML is a markup language that can be used to define the structure of a web page. HTML elements include
* headings
* paragraphs
* lists
* links
* and more!
The most recent major version of HTML is HTML5.

3
entries/Python.md Normal file
View File

@ -0,0 +1,3 @@
# Python
Python is a programming language that can be used both for writing **command-line scripts** or building **web applications**.

21
manage.py Normal file
View File

@ -0,0 +1,21 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'wiki.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()

0
wiki/__init__.py Normal file
View File

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

16
wiki/asgi.py Normal file
View File

@ -0,0 +1,16 @@
"""
ASGI config for wiki project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'wiki.settings')
application = get_asgi_application()

121
wiki/settings.py Normal file
View File

@ -0,0 +1,121 @@
"""
Django settings for wiki project.
Generated by 'django-admin startproject' using Django 3.0.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '%710m*zic)#0u((qugw#1@e^ty!c)9j04956v@ly(_86n$rg)h'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'encyclopedia',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'wiki.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'wiki.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'

22
wiki/urls.py Normal file
View File

@ -0,0 +1,22 @@
"""wiki URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("encyclopedia.urls"))
]

16
wiki/wsgi.py Normal file
View File

@ -0,0 +1,16 @@
"""
WSGI config for wiki project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'wiki.settings')
application = get_wsgi_application()