Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Django, can you automatically map URLs to view methods?

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?

like image 685
Nikki Erwin Ramirez Avatar asked Mar 24 '11 06:03

Nikki Erwin Ramirez


People also ask

How can I see all routes in Django?

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).

How do I pass URL parameters in Django?

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.

What is dynamic URL in Django?

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.


1 Answers

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.

like image 117
Yuji 'Tomita' Tomita Avatar answered Nov 09 '22 11:11

Yuji 'Tomita' Tomita