0

I am working on CS50 Web Development on the lesson of Django.

I want to pass a string from view.py to HTML as the URL link

here is the view.py

def randompage(request, name):
random_page = random.choice(util.list_entries())
return render(request, "encyclopedia/layout.html", {
"random_page": random_page})

and this is the HTML page

<a href="{% url 'randompage' random_page %}"> Random Page </a>

the urls.py

urlpatterns = [
path("", views.index, name="index"),
path("wiki/<str:name>", views.title, name= "title"),
path("wiki/", views.randompage, name= "randompage"),
path("searchresult", views.searchresult, name= "searchresult"),
path("newpage", views.newpage, name= "newpage")

]

the error code is

NoReverseMatch at / Reverse for 'randompage' with arguments '('',)' not found. 1 pattern(s) tried: ['wiki/$']

I know I shall you templatetag URL, but I don't really understand how it works and I cant find anyone have a similar situation with me.

1 Answers1

0

You can do this by using the following in your HTML template:

<a href="{% url 'title' randompage %}"> Random Page </a>
  • title is the path name from your urls.py
  • randompage is the parameter

Here is the relevant section of the Django docs.

MattRowbum
  • 2,162
  • 1
  • 15
  • 20
  • if the path i want to go is "wiki/", shall I just write ` Random Page ` – Vicent LHK ROT Jun 13 '21 at 02:50
  • @VicentLHKROT No, that won't work. The `{% url %}` tag needs a [URL Pattern Name](https://docs.djangoproject.com/en/stable/topics/http/urls/#naming-url-patterns) as the first argument. `title` is the name you have given that URL pattern in your urls.py file. – MattRowbum Jun 13 '21 at 02:54
  • @VicentLHKROT Just updated my answer. I had forgotten the quotation marks around the `url` tag. – MattRowbum Jun 13 '21 at 03:00
  • this time i have subsituded it with ` Random Page `, but the error code `django.urls.exceptions.NoReverseMatch: Reverse for 'title' with arguments '('',)' not found. 1 pattern(s) tried: ['wiki/(?P[^/]+)$']` occurs. I should have returned a string for randompage – Vicent LHK ROT Jun 13 '21 at 03:14
  • @VicentLHKROT If you are still having trouble, check the contents of `randompage` within your template. – MattRowbum Jun 13 '21 at 03:21
  • let me check it first, coz it supposes to pass a string, thank you – Vicent LHK ROT Jun 13 '21 at 03:31
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/233730/discussion-between-vicent-lhk-rot-and-mattrowbum). – Vicent LHK ROT Jun 14 '21 at 01:30