I'm trying to make an example for a product page where people can put designs on their product's. I'm using django and try to make my "designer" page behave differently on the type of product selected.
I want to have it behave like www.mysite.com/designer/foo where foo is the name of the product
I have gotten to make it work like www.mysite.com/designer?product=foo but i like the simplicity of the first url more and i can't imagine that wouldn't be possible.
urlpatterns = [
path('', overview, name='overview'),
path('designer/', designer, name='designer'),
path('administration/', administration, name='administration'),
path('admin/', admin.site.urls),
]
my url patterns are like this, i've tried fiddling around with some examples using regex behind the "/" after designer. but i can't get it to work, the server keeps trowing
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/designer/exampleA
I'm afraid i don't know where to start looking and how to properly formulate my question as webdeveloping is quite new to me.
CodePudding user response:
You can specify a pattern <str:designer>
where we make use of the <str:…>
path converter [Django-doc]:
urlpatterns = [
path('', overview, name='overview'),
path('designer/<str:designer>/', designer, name='designer'),
path('administration/', administration, name='administration'),
path('admin/', admin.site.urls),
]
Then your designer
view function should take designer
as parameter and handle this, so:
def designer(request, designer):
# …
here designer
is a string, so this will be 'foo'
if you visit /designer/foo/
.
CodePudding user response:
urls.py
urlpatterns = [
path('', overview, name='overview'),
path('designer/<str:no>', designer, name='designer'),
path('administration/', administration, name='administration'),
path('admin/', admin.site.urls),
]
views.py
def designer(request, no):
....
Django Dynamic URL Patterns
Being able to capture one or more values from a given URL during an HTTP request is an important feature Django offers developers. We already saw a little bit about how Django routing works, but those examples used hard-coded URL patterns. While this does work, it does not scale. Consider a website that has thousands of pages. You don’t necessarily need thousands of routes to serve those pages, but you do need the ability to capture variables from the URL so that one route pattern can handle many different pages. In this tutorial, we’ll explore a little bit more about Dynamic URL Patterns and values in Django.
Angle Brackets < > To capture a value in the URL pattern, you can use angle brackets. Below we have the hard-coded URL Patterns from the prior tutorial, and how we can rewrite three routes into one using angle brackets.