+ 3

How to link html pages according to user URL input in Django?

A link for example: 127.0.0.1:8000/wiki/html I want to link to that HTML page where the user types a link, after ...wiki/name_of_page. The stored html pages are in "encyclopedia/name_of_page.html" So if I enter now: 127.0.0.1:8000/wiki/css it must load the "encyclopedia/css.html" page. I don't want to hardcode the url in the views.py in search function. So what is the way to link to the page according to user search. urls.py code is: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:search>", views.search, name="search") ] view.py code is: from django.shortcuts import render from . import util def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def search(request, search): return render(request, "encyclopedia/name_of_page.html", { # make the url changeable as per the need "search": search })

12th Aug 2020, 5:13 PM
Adarsh Mamgain
Adarsh Mamgain - avatar
3 ответов
+ 3
re_path(r'^wiki/(?P<page>\d+)/
#x27;, views.getpage, name='page') #in views.py, def getpage(request, page): return render(request, 'encyclopedia/name_of_page.html', {'search' : page}) You can put the imports yourself... Hope that helps...
12th Aug 2020, 5:36 PM
Arnesh
Arnesh - avatar
+ 2
from what i seen here https://docs.djangoproject.com/en/3.1/topics/http/urls/ you can directly use search as if its from the url. so try using it. maybe like f"encyclopedia/{search}.html" also, make sure the file exist and the default page if the file doesnt exist
12th Aug 2020, 5:31 PM
Taste
Taste - avatar
+ 1
Adarsh Mamgain , instead of making separate pages.. You could make a model and render it in a template.. Also, search for get_object_or_404.
13th Aug 2020, 11:35 AM
Arnesh
Arnesh - avatar