Reputation: 99
I'm having trouble at having Django urlpatterns
catch a variable as an variable and instead take it as a set URL.
urlpatterns:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^about/', views.about),
url(r'^views/available_products/', views.available_products),
url(r'^views/productview/<int:product_id>/', views.productview)
]
When I host the server and go to /about/, /views/available_products/ or /admin/ they work fine, but trying to go to /views/productview/1/ gives a 404 error whereas going to /views/productview// gives a missing argument -error.
I tried to read the documentation and saw no obvious tell as to why my url variable argument wouldn't work, but clearly I'm doing something fundamentally wrong.
Here is an example error message from the debug page:
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/views/productview/12/
Using the URLconf defined in firstdjango.urls, Django tried these URL patterns, in this order:
^admin/
^about/
^views/available_products/
^views/productview/<int:product_id>/
The current path, views/productview/12/, didn't match any of these.
And here is the same error message but where the URL I try with is the same as in urlpatterns:
TypeError at /views/productview/<int:product_id>/
productview() missing 1 required positional argument: 'product_id'
Request Method: GET
Request URL: http://localhost:8000/views/productview/%3Cint:product_id%3E/
Django Version: 1.11.8
Exception Type: TypeError
Exception Value:
productview() missing 1 required positional argument: 'product_id'
Server time: Sat, 10 Feb 2018 12:25:21 +0000
views.py:
from django.http import HttpResponse, Http404
from django.shortcuts import render
def starting_instructions(request):
return render(request, "webshop/instructions.html", {})
def about(request):
return HttpResponse("about page")
def productview(request, product_id):
"""
Write your view implementations for exercise 4 here.
Remove the current return line below.
"""
return HttpResponse("product {}".format(product_id))
def available_products(request):
"""
Write your view implementations for exercise 4 here.
Remove the current return line below.
"""
return HttpResponse("View not implemented!")
Upvotes: 1
Views: 2783
Reputation: 2483
This url is not translated correctly.
see Request URL: http://localhost:8000/views/productview/%3Cint:product_id%3E/
You can use eighter path
or re_path
(which is similar to url and you can use regex in it so as you can use in url). So change your urlpatterns to.
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
path('about/', views.about),
path('views/available_products/', views.available_products),
path('views/productview/<int:product_id>/', views.productview)
]
EDIT
or if you really want to use url, use it like
url('^views/productview/(?P<product_id>\d+)/$', views.productview)
But using path
is the Django 2.0+ approach. Also replacing url
with re_path
which is the same.
Upvotes: 1