people. I'm a beginner Django developer so sorry if it's a basic question.
I have a webpage that shows a list of movies and each movie has a details view, but for some reason, the details view is never rendered.
#views.py
def index(request):
latest_movies = Movie.objects.order_by('-movie_id')[:5]
template = loader.get_template('ytsmirror/index.html')
context = {
'latest_movies' : latest_movies,
}
return HttpResponse(template.render(context, request))
def detail(request, movie_id):
movie = Movie.objects.get(movie_id=movie_id)
template = loader.get_template('ytsmirror/details.html')
context = {
'movie' : movie,
'plot': 'Lorem impsum',
}
return HttpResponse(template.render(context, request))
And my urls.py
#urls.py
from django.conf.urls import url
from . import views
app_name = 'ytsmirror'
urlpatterns = [
url(r'$', views.index, name='index'),
url(r'^(?P<movie_id>\d{4})$', views.detail, name='detail'),
]
When I try to reach /ytsmirror/4200/ for example, I don't get any error and Django apparently reaches the correct URL pattern but doesn't render the details view, it stays on the index view, without any change.
What am I doing wrong? Thanks.
url(r'$', views.index, name='index')
matches the end of the string, so basically it will match any url, that's why your code isn't working. You need to replace url(r'$', views.index, name='index')
with url(r'^$', views.index, name='index')
so that it will match only empty url
^
asserts position at start of the string
$
asserts position at the end of the string, or before the line terminator right at the end of the string (if any)