Named routes in Django
Routing routes in a web application allow you to define where a client's requests are going to be processed; specifying a path or URI to a specific template in Django.
Giving a name to our routes in our projects in Django is one of the features that modern frameworks have such as CodeIgniter, Laravel... and of course Django, which apart from working with MVC (or variants such as MTV) is always another A kind of pseudo layer, which is that of the routes, which we use to make the match between the URLs or URIs and the controller component that is in charge of processing the user's request.
Define routes names
We have to open the urls.py file of our app in Django and indicate a name of the application through the app_name, with this, we can reference the name that we define for each of the routes by prefixing the name of the app followed by : and then the name of the route.
Finally, through name, we indicate the name of the path as a parameter of the path function.
Here you can see an example of what was specified above:
app_name="gestion"
urlpatterns = [
path('',views.index),
path('detail/<int:pk>',views.show, name="show"),
]
We define the name of the app (app_name="management") and the example route (name="show").
Now, in our template, we can reference the name of the route, followed by the parameters (in case it has parameters):
<a href="{% url 'gestion:show' p.id %}">Ver</a>
And from a view, in case you want to redirect to another view, you can do something similar:
def update(request, pk):
product = get_object_or_404(Product, pk=pk)
...
return redirect('gestion:show',pk=pk)
In such a way that it will be easy to reference the named routes from any application that we have defined in a Django project.
- Andrés Cruz
Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter