Python Forum
Creating a link that takes the user to a random page
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Creating a link that takes the user to a random page
#1
Hey guys so I've been making some steps in my Wikipedia project but, as always, I run into mental roadblocks and I really need your stimulation to get me going.

Below are the steps of the project I have to complete. I have completed the index page, the wiki/<title> page, the create a new entry page and the random page.

Quote:Complete the implementation of your Wiki encyclopedia. You must fulfill the following requirements:
• Entry Page: Visiting /wiki/TITLE, where TITLE is the title of an encyclopedia entry, should render a page that displays the contents of that encyclopedia entry.
o The view should get the content of the encyclopedia entry by calling the appropriate util function.
o If an entry is requested that does not exist, the user should be presented with an error page indicating that their requested page was not found.
o If the entry does exist, the user should be presented with a page that displays the content of the entry. The title of the page should include the name of the entry.
• Index Page: Update index.html such that, instead of merely listing the names of all pages in the encyclopedia, user can click on any entry name to be taken directly to that entry page.
• Search: Allow the user to type a query into the search box in the sidebar to search for an encyclopedia entry.
o If the query matches the name of an encyclopedia entry, the user should be redirected to that entry’s page.
o If the query does not match the name of an encyclopedia entry, the user should instead be taken to a search results page that displays a list of all encyclopedia entries that have the query as a substring. For example, if the search query were Py, then Python should appear in the search results.
o Clicking on any of the entry names on the search results page should take the user to that entry’s page.
• New Page: Clicking “Create New Page” in the sidebar should take the user to a page where they can create a new encyclopedia entry.
o Users should be able to enter a title for the page and, in a textarea, should be able to enter the Markdown content for the page.
o Users should be able to click a button to save their new page.
o When the page is saved, if an encyclopedia entry already exists with the provided title, the user should be presented with an error message.
o Otherwise, the encyclopedia entry should be saved to disk, and the user should be taken to the new entry’s page.
• Edit Page: On each entry page, the user should be able to click a link to be taken to a page where the user can edit that entry’s Markdown content in a textarea.
o The textarea should be pre-populated with the existing Markdown content of the page. (i.e., the existing content should be the initial value of the textarea).
o The user should be able to click a button to save the changes made to the entry.
o Once the entry is saved, the user should be redirected back to that entry’s page.
• Random Page: Clicking “Random Page” in the sidebar should take user to a random encyclopedia entry.
• Markdown to HTML Conversion: On each entry’s page, any Markdown content in the entry file should be converted to HTML before being displayed to the user. You may use the python-markdown2 package to perform this conversion, installable via pip3 install markdown2.
o Challenge for those more comfortable: If you’re feeling more comfortable, try implementing the Markdown to HTML conversion without using any external libraries, supporting headings, boldface text, unordered lists, links, and paragraphs. You may find using regular expressions in Python helpful.

I'm really having an issue with the search field. I can't conceptualize on how to run the search since I'm searching through a bunch of files instead of a SQL database search which is more typical for me to understand.

Below is all my code - can you guys give me some ideas on how to tackle this? I'm going to do the "edit page" and "markup to html" translations last since those are going to give me issues as well.

Thank you!

util.py :
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
views.py :

from django.shortcuts import render
from django import forms
from collections import Counter
import random
import markdown2
from django.contrib import messages

from . import util


def index(request):
    return render(request, "encyclopedia/index.html", {
        "entries": util.list_entries()
    })

def wiki(request, title):
    return render(request, "encyclopedia/wiki.html", {
        "entries": util.get_entry(title)
    })

def create(request):
    if request.method == "POST":
        title = request.POST.get("title")
        content = request.POST.get("content")
        test = util.get_entry(title)
        if test != None:
            messages.error(request, "username or password not correct")
            return render(request, "encyclopedia/create.html", {
            "entries": util.list_entries()
        })
            
        else:
            return render(request, "encyclopedia/create.html", {
            "entries": util.save_entry(title, content)
        })
    else:
        title = ""
        content = ""
        return render(request, "encyclopedia/create.html", {
            "entries": util.list_entries()
        })

def randompage(request):
    return render(request, "encyclopedia/randompage.html", {
        "entries":  random.choice(util.list_entries())
    })
    
    
urls.py :

from django.urls import path

from . import views


urlpatterns = [
    path("", views.index, name="index"),
    path("wiki/<str:title>", views.wiki, name="wiki"),
    path("create", views.create, name="create"),
    path("randompage", views.randompage, name="randompage")
]
layout.html:

{% load static %}

<!DOCTYPE html>

<html lang="en">
    <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>
                    <input class="search" type="text" name="search" placeholder="Search Encyclopedia">
                </form>
                <div>
                    <a href="{% url 'index' %}">Home</a>
                </div>
                <div>
                    <a href="{% url 'create' %}">Create New Page</a>
                </div>
                <div>
                    <a href="{% url 'randompage' %}">Random Page</a> 
                </div>
                {% block nav %}
                {% endblock %}
            </div>
            <div class="main col-lg-10 col-md-9">
                {% block body %}
                {% endblock %}
            </div>
        </div>

    </body>
</html>
wiki.html:

{% extends "encyclopedia/layout.html" %}

{% block title %}
    Encyclopedia
{% endblock %}

{% block body %}

    <ul>
            
            {{ entries }}
            
        
    </ul>

{% endblock %}
index.html:

{% 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 %}
create.html:

{% extends "encyclopedia/layout.html" %}

{% block title %}
    Encyclopedia
{% endblock %}

{% block body %}

    
       
            <p>Create new Wiki entry</p>
            
          <form
       name="frmInfo3"
       action="/create"
       method="post"     >{% csrf_token %}
                <input type="text" name="title" placeholder="Enter Title" required>
                <input type="textarea" size=100 name="content" placeholder="Enter content with title first in Markdown language" required>
                <input type="submit" id="create" value="Create New Entry" />
         </form>   
     {% for message in messages %}

                    <div class="alert alert-success">
                        <a class="close" href="#" data-dismiss="alert">×</a>

                        {{ message }}

                    </div>
            {% endfor %}
  

{% endblock %}
randompage.html:

{% extends "encyclopedia/layout.html" %}

{% block title %}
    Encyclopedia
{% endblock %}

{% block body %}
    <h1>random</h1>
    <a href="wiki/{{ entries }}">{{ entries }}</a>
    

{% endblock %}
Reply
#2
Well that is quite a long story. Not everybody wants to read all this. And you are not very specific about what you are asking. From the title we learn: "Creating a link that takes the user to a random page". Is that what you want? Does it not give the expected result or do you get an error message?
You will have to elaborate on what is happening. Test your code bit by bit. Is it the function util.list_entries() that does not give the expected result?
Reply
#3
Also, after reading a file, what kind of data do you get back (i.e. a string of something else) and what have you looked up to be able to help you get the result you want?
Reply
#4
(Jul-04-2020, 09:54 AM)ibreeden Wrote: Well that is quite a long story. Not everybody wants to read all this. And you are not very specific about what you are asking. From the title we learn: "Creating a link that takes the user to a random page". Is that what you want? Does it not give the expected result or do you get an error message?
You will have to elaborate on what is happening. Test your code bit by bit. Is it the function util.list_entries() that does not give the expected result?

Sorry I edited my original post since I figured that part out. I forgot to change the title - didn't know you could.

Right now I'm having trouble conceptualizing on how to do the search function.

When I type in something into the search box and press enter, it takes me to the original search page but with a ?search=<input> extension. I didn't type that code so I'm assuming that's automatic from a search box.

I'm wondering how I can get that variable from the URL and use it to search through the markdown files I have.
Reply
#5
Have you set the correct method for the form (i.e. the HTTP verb that's used when you submit it)?
Reply
#6
Yeah that was the issue I figured it out! Thanks. I'm working on the edit page now. What I'll need help with is converting the markdown to html. I don't quite get how the markdown to html thing works can you help explain it? THanks
Reply
#7
Have you looked at the documentation for the library that has been suggested, or are you wanting to implement it yourself? Also, what exactly is it you don't understand? Do you know what Markdown is?
Reply
#8
I think I'll save the markdown for last since it really confuses me. I'm not sure how it's any better than html. Especially since I have to convert it to HTML anyways.

But I'll save that.

For now I really need help revising my code. I'm getting really confused can u please take a look? I made a new post. Thanks
Reply
#9
Browsers only render HTML, so if the formatting of your text is expressed in another way (e.g Markdown) and you want that formatting to be respected on web pages, then you need to convert it to HTML.
Reply
#10
OK I understand but that seems like something I can change at the end once I have the markdown showing up properly. I'll probably have to ask you to help once I start that phase after I finish this edit stuff.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Issue Creating New Link Using Text oca619 1 1,927 May-05-2019, 09:07 AM
Last Post: Yoriz
  Creating code to make up to 4 turtle move simultaneously in a random heading J0k3r 3 5,494 Mar-05-2018, 03:48 PM
Last Post: mpd
  User input only takes the last number Austin11 16 8,049 Nov-28-2017, 11:20 PM
Last Post: Prrz

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020