Reverse for "" not found. "" is not a valid view function or pattern name

I am a beginner in django and while I learnin dajngo from youtube I got this problem note that I do every thing like course step by step and I searched on solution to this problem for hours and I didn't find anything. when I pass url dynamically it causes a problem "Reverse for 'room' not found. 'room' is not a valid view function or pattern name."

home.html

{% extends "main.html" %}


{% block content %}
<h1>Home Template</h1>

<div>
    <div>
        {% for room in rooms %}
            <div>
                 <h3>{{ room.id }} -- <a href="{% url 'room' room.id %}">{{ room.name }}</h3></a>
            </div>
        {% endfor %}
    </div>
</div>
    
{% endblock %}

room.html

{% extends 'main.html' %}


{% block content %}

<h1>Room Page </h1>

<h1>{{ room_r.name }}</h1>
    
{% endblock content %}
    

views.py

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

rooms = [
    {'id': 1, 'name': 'lets learn python!'},
    {'id': 2, 'name': 'Desgin with me'},
    {'id': 3, 'name': 'Frontend developer'},
]

def home(request):
    context = {'rooms': rooms}
    return render(request, 'base/home.html', context)

def room(request, pk):
    room = None
    for i in rooms:
        if i['id'] == int(pk):
            room = i
        
    context = {'room_r': room}
    return render(request, 'base/room.html',context)

urls.py

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

rooms = [
    {'id': 1, 'name': 'lets learn python!'},
    {'id': 2, 'name': 'Desgin with me'},
    {'id': 3, 'name': 'Frontend developer'},
]

def home(request):
    context = {'rooms': rooms}
    return render(request, 'base/home.html', context)

def room(request, pk):
    room = None
    for i in rooms:
        if i['id'] == int(pk):
            room = i
        
    context = {'room_r': room}
    return render(request, 'base/room.html',context)

for using url like that you should specify the name if the app inside 'urls.py' of that app and you should gave each path a name

room_app/urls.py

app_name = 'room'

urlpatterns = [
    path('', index, name='index'), 
    #your index view
]

then inside your html file use url like :

<a href="{% url 'room:index' room.id %}">{{ room.name }}</a>

remember 'room' is app name | 'index' is url name

Back to Top