Given a view like this:
# my_app/views.py
def index(request):
...
def list(request):
...
def about(request):
...
Instead of explicitly declaring the urls in urls.py
for each method in the view:
# urls.py
url(r'^index$', 'my_app.views.index'),
url(r'^list$', 'my_app.views.list'),
url(r'^about$', 'my_app.views.about'),
...
Is it possible to just give the URL dispatcher the view (my_apps.views
) and have it handle all the view's methods?
In case you are using DRF, you can print all the URL patterns for a particular router by printing the urlpatterns from router. get_urls() (within your Django app's urls.py file).
Django URL pass parameter to view You can pass a URL parameter from the URL to a view using a path converter. Then “products” will be the URL endpoint. A path converter defines which type of data will a parameter store. You can compare path converters with data types.
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.
I suppose you can have one view that captures a url regexp,
r'^(?P<viewtype>index|list|about)/$', 'myview'
with a view that handles the captured parameter.
def myview(request, viewtype):
if viewtype == 'index':
return http.HttpResponse("I'm the index view")
elif viewtype == 'list':
return http.HttpResponse("I'm the list view')
But I'd really recommend keeping your view logic separated for clarity. It's much easier to follow 3 different views with their specific functions than 3 if / then statements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With