How to use a single application to satisfy multiple URLs in Django

I am trying to use a single application to satisfy multiple URLs. That is, I want url /blog/ and /job/ use the same application, but different types. There are several ways to do this, I am sure, but none of them seem very clean. Here is what i am doing right now

 # /urls.py urlpatterns = patterns("", (r"^(blog|job)/", include("myproject.myapp.urls")), ) # /myapp/urls.py urlpatterns = patterns("myproject.myapp.views", (r"^(?P<id>\d+)/edit/$", "myproject.myapp.views.edit"), (r"^(?P<id>\d+)/delete/$", "myproject.myapp.views.delete"), (r"^(?P<id>\d+)/update/$", "myproject.myapp.views.update"), (r"^insert/$", "myproject.myapp.views.insert"), ) urlpatterns += patterns("", (r"^(?P<object_id>\d+)/$", "django.views.generic.list_detail.object_detail", info_dict, "NOIDEA-detail"), (r"^/$", "django.views.generic.list_detail.object_list", info_dict, "NOIDEA-community"), ) # /myapp/views.py def edit(request, type, id): if (type == "blog"): editBlog(request, id) else (type == "job") editJob(request, id) def editBlog(request, id): # some code def editJob(request, id): # some code 

I ended up breaking it all down into several models and browsing the files to make the code cleaner, but the above example doesn’t take into account things like reverse URL lookups that breaks all calls to my template {% url %} .

Initially, I had blogs, jobs, events, contests, etc., all of which live in their applications, but all of their functions are so similar that it makes no sense to leave it this way, so I tried to combine them ... and it happened. Do you see the names "NOIDEA-detail" and "NOIDEA-community" in my general views? Yes, I do not know what to use there: - (

+4
source share
2 answers

You can have several modules that define URLs. You can have /blog/ urls in myapp/urls.py and /job/ urls in myapp/job_urls.py . Or you can have two modules in the urls .

Alternatively, you can manually specify your URL definitions:

 urlpatterns = patterns("myproject.myapp.views", (r"^jobs/(?P<id>\d+)/edit/$", "myproject.myapp.views.edit"), (r"^jobs/(?P<id>\d+)/delete/$", "myproject.myapp.views.delete"), (r"^jobs/(?P<id>\d+)/update/$", "myproject.myapp.views.update"), (r"^jobs/insert/$", "myproject.myapp.views.insert"), ) urlpatterns += patterns("", (r"^blog/(?P<object_id>\d+)/$", "django.views.generic.list_detail.object_detail", info_dict, "NOIDEA-detail"), (r"^blog/$", "django.views.generic.list_detail.object_list", info_dict, "NOIDEA-community"), ) 

And then set them as:

 urlpatterns = patterns("", (r"", include("myapp.urls")), ) 

Personally, I would choose a more RESTful URL definition. For example, blog/(?P<post_id>\d+)/edit/$ .

+4
source

Looks good. If you want a reverse search, just provide a different reverse name for each URL format, even if they point to the same kind.

0
source

All Articles