Python Forum
Help with new Django Project
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with new Django Project
#1
Hey guys I'm onto a new project and I'm using Django now instead of Flask. Please forgive me but sometimes I need to be prodded a bit to get started - once you guys get me going in the right direction I usually figure it out.

I'm creating a Wikipedia page and I have to make it so that the user can go to /wiki/<title> with title being a wikipedia entry like HTML or CSS and it will take them to a page of the information.

I'm getting an error when I go to the wiki/HTML (and the others). Can anyone see what I'm doing wrong?

view.py:

from django.shortcuts import render

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/{title}.html", {
        "entries": util.get_entry(title)
    })
url.py :

from django.urls import path

from . import views


urlpatterns = [
    path("", views.index, name="index"),
    path("wiki/<str:title>", views.wiki, name="wiki"),
]
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
Error:
TemplateDoesNotExist at /wiki/HTML encyclopedia/wiki/{title}.html Request Method: GET Request URL: http://127.0.0.1:8000/wiki/HTML Django Version: 3.0.8 Exception Type: TemplateDoesNotExist Exception Value: encyclopedia/wiki/{title}.html Exception Location: C:\Python38\lib\site-packages\django\template\loader.py in get_template, line 19 Python Executable: C:\Python38\python.exe Python Version: 3.8.2 Python Path: ['C:\\school\\project1', 'C:\\Python38\\python38.zip', 'C:\\Python38\\DLLs', 'C:\\Python38\\lib', 'C:\\Python38', 'C:\\Python38\\lib\\site-packages'] Server time: Thu, 2 Jul 2020 21:28:38 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: C:\school\project1\encyclopedia\templates\encyclopedia\wiki\{title}.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Python38\lib\site-packages\django\contrib\admin\templates\encyclopedia\wiki\{title}.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Python38\lib\site-packages\django\contrib\auth\templates\encyclopedia\wiki\{title}.html (Source does not exist) Traceback Switch to copy-and-paste view C:\Python38\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) … ▶ Local vars C:\Python38\lib\site-packages\django\core\handlers\base.py in _get_response response = self.process_exception_by_middleware(e, request) … ▶ Local vars C:\Python38\lib\site-packages\django\core\handlers\base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars C:\school\project1\encyclopedia\views.py in wiki return render(request, "encyclopedia/wiki/{title}.html", { … ▶ Local vars C:\Python38\lib\site-packages\django\shortcuts.py in render content = loader.render_to_string(template_name, context, request, using=using) … ▶ Local vars C:\Python38\lib\site-packages\django\template\loader.py in render_to_string template = get_template(template_name, using=using) … ▶ Local vars C:\Python38\lib\site-packages\django\template\loader.py in get_template raise TemplateDoesNotExist(template_name, chain=chain) … ▶ Local vars
Reply
#2
OK I got it to where it's spitting out the information from GitHub Markdown and showing it to me.

Now I'm onto the next step which is the search engine. I'm not sure where I would type my if statements. Do I do this in the view? Or in the manage.py? I'm a little confused as how to go about it can someone try to get me started?

here's what I have :

view.py:

from django.shortcuts import render

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 search(request, search):
    return render(request, "encyclopedia/index.html", {
        "entries": util.get_entry(search)
    })
urls.py:

from django.urls import path

from . import views


urlpatterns = [
    path("", views.index, name="index"),
    path("wiki/<str:title>", views.wiki, name="wiki"),
]
#!/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()
    
Thanks!
Reply
#3
Why would you assume you need to touch manage.py at all? The comment on line 2 tells you it's not really part of the app (as do the docs). The views are your request handlers.
Reply
#4
OK that makes sense. I'm trying some simple code to see if it works. For some reason it's not printing the search results for me.

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>
                    Create New Page
                </div>
                <div>
                    Random Page 
                </div>
                {% block nav %}
                {% endblock %}
            </div>
            <div class="main col-lg-10 col-md-9">
                {% block body %}
                {% endblock %}
            </div>
        </div>

    </body>
</html>
views.py:

from django.shortcuts import render

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 search(request, search):
    search = request.form.get("search")
    print(search)
    return render(request, "encyclopedia/search.html", {
        "entries": util.get_entry(search)
    })
    

here's my util.py file:

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
Reply
#5
What have you done to see where the problem lies?
Reply
#6
I've triple checked the code. It all checks out to me. If what you're saying is true about the statements being in the view, why wouldn't it easily print out the input from the search bar?
Reply
#7
Have you checked what values you get back in the relevant variables? Checking over code is one thing, but one also usually needs to see what is happening when it's executed. Also, what does the template for viewing the search results look like?
Reply
#8
That's what I'm doing here I'm trying to print out the relevant variable (the input in the search form) and I'm not getting it to print out. How else can I check it?

I don't have the template yet for the search results for now I'm just trying to get it to work.
Reply
#9
We'll, you're only printing the input, not the result you get using that value for the search.
Reply
#10
yes but i'm just trying to print the input to make sure it's working, you know? Kind of a troubleshoot.

Do you know why it's not working?

If I can't get the value to even work, then I can't bother with the search.

I'm really confused as to why it's not printing out the simple request. I don't think I'm doing the view right or something. When I type in a search I get the following URL: /?search=HTML and I cannot find that code anywhere. why is it automatically making that the url and if that's the proper way to do it - how can I extract the search value variable to use in my code?

I can't find the correct syntax anywhere. I don't understand why everything has to seem so complicated. It's so hard to find solid information. Please help if you can. Thanks.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Hello I’m trying to run a Django python project on docker but when I try to build the Nessa404 1 1,529 Apr-22-2022, 12:25 PM
Last Post: VadimCr

Forum Jump:

User Panel Messages

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