Fundamentos de Django

1

¿Qué es Django?

2

¿Cómo instalar Django?

3

Entendiendo la arquitectura de Django

4

Qué es el patrón MVT (Model, View y Template)

La M en el Patrón: Modelo

5

Introducción a Modelos y Bases de Datos

Manejo Avanzado de Modelos y Bases de Datos

6

Gestión de Modelos y Bases de Datos en Django con SQLite

7

Inserción de Datos con Django

8

Actualización y Eliminación de Datos en Django

Relaciones y Asociaciones entre Modelos

9

Creación y Gestión de Relaciones entre Modelos en Django

10

Relaciones Muchos a Muchos (N:N) en Django

11

Relaciones Uno a Uno (1:1) en Django

12

Queries y Filtros en Django: Optimización y Estrategias Avanzadas

Configuración de URLs y Vistas Avanzadas

13

Gestión de URLs en Django: Configuración, Rutas y Mejores Prácticas

14

Vistas Basadas en Clases en Django

La T en el Patrón: Plantillas o Templates

15

Personalización de Interfaz con Plantillas en Django

Desarrollo de Aplicaciones en Django

16

Configuración del Proyectos en Django

17

Creación del Modelo para la Aplicación 'Products' en Django

18

Cómo Crear Migraciones de Datos en Django

19

Creación de la Aplicación 'Products' con Formularios en Django

20

Integracion de TailwindCSS en Django

21

Django Admin

22

Manejo de Sesiones en Django

23

Manejo de Órdenes en CoffeShop

24

Manejo de Pedidos en CoffeShop

25

Mixings en vistas basadas en clases

26

Agregar productos a la orden

Django Rest Framework

27

Django REST Framework

Despliegue de aplicaciones Django

28

Configurar PostgreSQL en AWS con Django

29

Variables de entorno en Django

30

¿Cómo usar Unit Testing en Django?

31

Debugging en Django

32

Desplegar aplicaciones de Django en AWS

You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
7 Hrs
14 Min
58 Seg
Curso de Django

Curso de Django

Luis Martínez

Luis Martínez

Gestión de URLs en Django: Configuración, Rutas y Mejores Prácticas

13/32
Resources

Setting up URLs in Django is essential for organizing your project and making navigation easier.

How to create a URL file in Django?

First, you must create an urls.py file in each application you develop. For example, if you have an application called MyFirstApp, you must create an urls.py file inside this application.

  1. Create the file: In the MyFirstApp application, create a file called urls.py.
  2. Copy and paste basic settings: You can copy the basic settings from another URLs file and modify them as needed.
  3. Remove unnecessary links and imports: Keep only what is necessary for your application.
from django.urls import pathfrom. import views urlpatterns = [ path('list/', views.myView, name='list'), ]

How to include URLs of an application in the project?

To include the URLs of an application in the main project, follow these steps:

  1. Modify the URLs file of the project: add a new path that includes the URLs of your application.
from django.urls import include, path urlpatterns = [ path('carts/', include('myFirstApp.urls')), ]
  1. Import the include: Make sure to import include from django.urls.

How to set up a development server?

To test the changes, run the development server:

python manage.py runserver

This will start the server and you will be able to see the changes in real time.

How to create dynamic URLs?

To create URLs that accept dynamic parameters, follow these steps:

  1. Define a dynamic URL: Use the < and > characters to specify the data type and parameter name.
urlpatterns = [ path('detail/<int:id>/', views.detail, name='detail'), ]
  1. Modify the view to accept parameters: Make sure your view accepts the corresponding parameters.
def detail(request, id): return HttpResponse(f"ID is {id}")

How to handle different data types in URLs?

Django allows you to convert different data types in URLs, such as integers and strings:

  1. Integers: use <int:name> for integers.
  2. Strings: Use <str:name> for strings.
urlpatterns = [ path('brand/<str:brand>/', views.brand, name='brand'), ]

How to test dynamic URLs in the browser?

  1. Test with integers: Access a URL that requires an integer, such as detail/1/.
  2. Test with text strings: Access a URL that requires a text string, such as brand/mazda/.

Contributions 19

Questions 1

Sort by:

Want to see more contributions, questions and answers from the community?

Reto resuelto: ```js from django.http import HttpResponse from django.urls import path from .models import Author, Profile def my_view(request, *args, **kwargs): print(args) print(kwargs) return HttpResponse("") def author_view(request, *args, **kwargs): print(args) print(kwargs) author = Author.objects.get(id=kwargs['id']) profile = Profile.objects.get(author_id=kwargs['id']) return HttpResponse(f"Author: {author.name} - Website: {profile.website} - Biografia: {profile.biography} ") urlpatterns = [ path('listado/', my_view), path('detalle/<int:id>', my_view), path('marcas/<str:brand>', my_view), path('autor/<int:id>', author_view), ] ```
Reto: **views.py** en **my\_first\_app:** ![](https://static.platzi.com/media/user_upload/image-97a07da7-43ce-48a5-bbfa-378c2e35f110.jpg) dentro de templates/my\_first\_app/ cree el archivo author\_profile.html ![](https://static.platzi.com/media/user_upload/image-d3a4a244-b385-4d87-9de4-8258de90067b.jpg) Luego dentro de my\_first\_app modifique el archivo urls.py de la siguiente manera: ![](https://static.platzi.com/media/user_upload/image-4ef1414e-d1f4-4f34-8866-33da44aa5930.jpg) Luego de eso modifique el archivo urls.py dentro de my\_\_first\_project: ![](https://static.platzi.com/media/user_upload/image-f7699ec1-4cc6-480c-a2bb-07fc8eeee200.jpg) Al modificar el urls del proyeto en la linea 22 quitando carros, al ejecutar el código las rutas quedan: ![](https://static.platzi.com/media/user_upload/image-ca856c41-24e0-4902-b1cb-4d776448f4b4.jpg) Finalmente para ver el el perfil del autor: ![](https://static.platzi.com/media/user_upload/image-7fba8698-646f-479b-b9ac-1b01cfd67659.jpg)
Me sale un warning que las urls deben empezar sin la barra, así path("/listado", my\_view) debe ser cambiado a path("listado", my\_view). Sigue funcionando igual, pero desaparece el warning
en mi punto de vista, vi que varios crean su url concatenando su ID, siento que no es nada seguro porque se podria hacer muchas cosas con ese id que tiene en la url, lo conveniente es manejarlo oculto mas no mostrar por ID, es mi punto de vista ya que hay otros metodos de como hacerlo
Reto completado: urls.py de my first project ```python from django.contrib import adminfrom django.urls import path, include urlpatterns = \[ path('admin/', admin.site.urls), path('carros/', include('my\_first\_app.urls')), path('profiles/', include('my\_first\_app.urls'))] ``` luego urls.py de my first app: ```python from django.http import HttpResponsefrom django.urls import pathfrom my\_first\_app.views import author\_profile, list\_cars def my\_view(request, \*args, \*\*kwargs): print(args) print(kwargs) return HttpResponse("") urlpatterns = \[ path("listado/", list\_cars), path("detalle/\<int:id>", my\_view), path("marcas/\<str:brand>", my\_view), path("author-profile/\<int:id>", author\_profile)] ``` después en views.py de my first app: ```python from django.shortcuts import renderfrom my\_first\_app.models import Car, Profile \# Create your views here. def list\_cars(request): car\_list = Car.objects.all() context = { "car\_list": car\_list } return render(request, "my\_first\_app/car\_list.html", context) def author\_profile(request, id): profile = Profile.objects.get(id=id) print(f'this is the profile! {profile}') context = { "profile": profile } return render(request, "my\_first\_app/author\_profile.html", context) ``` finalmente en el html: ```html \\<html lang="en"> \<head> \<meta charset="UTF-8" /> \<meta name="viewport" content="width=device-width, initial-scale=1.0" /> \<title>Profile\</title> \</head> \<body> \

This the profile of {{ profile.author }}\

\<article>{{profile.biography}}\</article> \

Visit the website in this link \{{profile.website}}\ \

\</body>\</html> ```
Quise hacer que la URL tenga mas sentido mostrando el id del autor y el id del perfil a la vez (un poco mas semantica), por lo que lo hice de la siguiente manera, creando una vista para el autor y dentro de esta, un boton para ver su perfil: **Vistas:** author\_list.html ```js <html lang="es"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Lista de Autores</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" /> </head> <body>
<h1 class="my-4">Lista de Autores
    {% for author in author_list %}
  • <h6> {{ author.name }} </h6>

    Fecha de Nacimiento: {{ author.birth_date }}

  • {% endfor %}
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> </body> </html> ```author\_details.html ```js <html lang="es"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Detalle del Autor</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" /> </head> <body>
<h1 class="my-4">Detalle del Autor Volver a los Autores
<h5 class="card-title">{{ author.name }}</h6>

Fecha de Nacimiento: {{ author.birth_date }}

{% if author.profile.id %} Ver Perfil {% endif %}
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> </body> </html> ```author\_profile.html ```js <html lang="es"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Perfil de {{ author_profile.author }}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" /> </head> <body>
<h1 class="my-4">Perfil de {{ author_profile.author }} Volver al Autor
<h5 class="card-title">{{ author_profile.author }}</h6>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> </body> </html> ```**Python** views.py ```python froms django.shortcuts import render from my_first_app.models import Author, Profile # author list view def authors_view(request): author_list = Author.objects.all() context = { "author_list": author_list } return render(request, "my_first_app/author_list.html", context) # author detail view def author_view(request, *args, **kwargs): author = Author.objects.get(id=kwargs.get("author_id")) context = { "author": author } return render(request, "my_first_app/author_detail.html", context) # author profile view def author_profile_view(request, *args, **kwargs): author_profile = Profile.objects.get(author=kwargs.get("author_id"), id=kwargs.get("profile_id")) context = { "author_profile": author_profile } return render(request, "my_first_app/author_profile.html", context) ```urls.py ```js from django.urls import path from my_first_app.views import authors_view, author_view, author_profile_view urlpatterns = [ path("autores", authors_view), path("autor/<int:author_id>", author_view), path("autor/<int:author_id>/perfil/<int:profile_id>", author_profile_view) ] ```
books\_authors\_list.html: ![](https://static.platzi.com/media/user_upload/books_and_authors-b155caba-2bcf-4e01-9697-4b655463c096.jpg) urls.py ![](https://static.platzi.com/media/user_upload/books_and_authors_urls-901b3fc8-6f35-4080-9c43-37bf2c739a4d.jpg) views.py ![](https://static.platzi.com/media/user_upload/books_and_authors_views-21480146-48bb-4c2a-a923-029535f5c40c.jpg)
HTML: ```html <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Car List</title> </head> <body>

Author: {{author.name}}

  • Nombre: {{author.name}} - Año de nacimiento: {{author.birth_date}}
</body> </html> ```Y la view: ```python def author_detail_view(request, id:int): author = Author.objects.get(id=id) context = { 'author': author } return render(request, "my_first_app/author.html", context) ```
Comparto mi solución al reto: **- views.py:** from django.shortcuts import render, get\_object\_or\_404from first\_app.models import Author, Profile def authors\_information(request, id):    author = get\_object\_or\_404(Author, pk=id) # Obtiene el autor por su pk (primary key)    profile = get\_object\_or\_404(Profile, author=author) # Obtiene el perfil asociado al autor    context = {'profile': profile}    return render(request, 'authors\_information.html', context) **- urls.py (my\_first\_proyect):** from django.contrib import adminfrom django.urls import path, include urlpatterns = \[    path('admin/', admin.site.urls),    path("carros/", include("first\_app.urls")),    path("authors/", include("first\_app.urls"))] **- urls.py (first\_app)** from django.urls import pathfrom first\_app.views import my\_view, authors\_information urlpatterns = \[    path("listado", my\_view),    path("detalle/\<int:id>", my\_view),    path("marcas/\<str:brand>", my\_view),    path("author-biography/\<int:id>/", authors\_information, name="author\_biography")] **- HTML:** \\<html lang="es">\<head>    \<meta charset="UTF-8">    \<meta name="viewport" content="width=device-width, initial-scale=1.0">    \<title>Información del Autor\</title>    \<style>        table {            border-collapse: collapse;            width: auto; /\* Importante: Ancho automático \*/            table-layout: fixed; /\* Ancho fijo para las columnas \*/        }         th, td {            border: 1px solid black;            padding: 8px;            text-align: left;            word-wrap: break-word; /\* Permite que las palabras largas se rompan \*/            max-width: 300px; /\* Ancho máximo para las celdas \*/         }        th {            background-color: #f2f2f2;        }    \</style>\</head>\<body>    \

Información del Autor\

    \        \            \                \                \                \            \        \        \            \                \                \                \            \        \    \
Autor\Sitio Web\Biografía\
{{ profile.author }}\\{{ profile.website }}\\{{ profile.biography }}\
\</body>\</html> Me apoyé en mi querido amigo ChatGPT para crear el HTML y tambien para agregar una funcion de Django (get\_object\_or\_404()), que ayuda un poco con el manejo de errores. ![](https://static.platzi.com/media/user_upload/image-35d73329-7883-4c9b-a7b7-cecce394abdc.jpg)
Reto resuelto usando filter que vimos en clases pasadas: ```python from django.http import HttpResponse from django.urls import path from .models import Author, Profile def my_view(request, *args, **kwargs): print(args) print(kwargs) return HttpResponse("") def author_view(request, *args, **kwargs): print(kwargs) print(kwargs["author"]) author = Author.objects.filter(name=kwargs["author"]).first() profile = Profile.objects.filter(author=author).first() print(author) print(profile.biography) print(profile.website) return HttpResponse(f"Author: {author.name} - Website: {profile.website} - Biografia: {profile.biography} ") urlpatterns = [ path("listado/", my_view), path("detalle/<int:id>", my_view), path("marcas/<str:brand>", my_view), path("perfiles/<str:author>", author_view) ] ```
Reto resuelto usando filter que vimos en clases pasadas: `from`` django.http ``import`` HttpResponse``from`` django.urls ``import`` path``from`` .models ``import`` Author, Profile` `def ``my_view``(request, *args, **kwargs):    print(args)    print(kwargs)    ``return`` HttpResponse("")` `def ``author_view``(request, *args, **kwargs):    print(kwargs)    print(kwargs["author"])    author = Author.objects.filter(name=kwargs["author"]).first()    profile = Profile.objects.filter(author=author).first()    print(author)    print(profile.biography)    print(profile.website)    ``return`` HttpResponse(f"Author: {author.name} - Website: {profile.website} - Biografia: {profile.biography} ")` `urlpatterns = [    path("listado/", my_view),    path("detalle/<int:id>", my_view),    path("marcas/<str:brand>", my_view),    path("perfiles/<str:author>", author_view)]`
![](https://static.platzi.com/media/user_upload/Captura%20de%20pantalla%20%2819%29-4e2799d1-57a8-4300-a4de-6193a4c642c8.jpg)tengo un problema
![](https://static.platzi.com/media/user_upload/image-facec073-23ef-4fb4-832d-614b0f19f5ee.jpg)![](https://static.platzi.com/media/user_upload/image-14962c67-1ae9-410c-bb42-dd4f125b2ca9.jpg) ![](https://static.platzi.com/media/user_upload/image-ae3efdf5-7495-4f60-a002-bd2cb9ec879a.jpg)
Vista: from django.contrib import adminfrom django.urls import path, includefrom django.http import HttpResponsefrom django.urls import pathfrom my\_first\_app.views import my\_view, my\_view2\\<html lang="en">\<head>    \<meta charset="UTF-8">    \<meta name="viewport" content="width=device-width, initial-scale=1.0">    \<title>Lista de Autos\</title>\</head>\<body>    \

Perfil del Autor {{ profile.author.name }}\

    \        {% for author in author\_biography %}        \            \            \            \        \        {% endfor %}    \
{{ author.author }}\{{ author.website }}\{{ author.biography }}\
\</body>\</html> urlpatterns = \[    path("listado/", my\_view, name="car\_list"),    path("detalle/\<int:id>", my\_view),    path("marcas/\<str:brand>", my\_view),    path("autor/\<str:author\_name>", my\_view2, name="author\_biography"),] urlpatterns = \[    path('admin/', admin.site.urls),    path("carros/", include("my\_first\_app.urls")),    path("biografia/",include("my\_first\_app.urls"))] ```js from django.shortcuts import render from my_first_app.models import Car, Profile # Create your views here. def my_view(request): car_list = Car.objects.all() context = { "car_list": car_list } return render(request, "my_first_app/car_list.html", context) def my_view2(request,author_name): author_biography = Profile.objects.filter(author__name=author_name) context = { "author_biography": author_biography } return render(request, "my_first_app/car_list.html", context) ```Urls: ```js from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path("carros/", include("my_first_app.urls")), path("biografia/",include("my_first_app.urls")) ] ```Urls de my\_first\_app: ```js from django.http import HttpResponse from django.urls import path from my_first_app.views import my_view, my_view2 urlpatterns = [ path("listado/", my_view, name="car_list"), path("detalle/<int:id>", my_view), path("marcas/<str:brand>", my_view), path("autor/<str:author_name>", my_view2, name="author_biography"), ] ```template: ```js <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Lista de Autos</title> </head> <body>

Perfil del Autor {{ profile.author.name }}

{% for author in author_biography %} {% endfor %}
{{ author.author }} {{ author.website }} {{ author.biography }}
</body> </html> ```
Algo mas de las URLs en Django en los primeros pasos con Django documentation: <https://docs.djangoproject.com/en/5.0/intro/tutorial01/#path-argument-route>
Comparto mi solución para mostrar la información del perfil de un Autor: **views.py (my\_first\_app):** ![](https://static.platzi.com/media/user_upload/image-d5186144-425c-4564-aefb-f3b52ff67c75.jpg) **urls.py (my\_first\_app):** ![](https://static.platzi.com/media/user_upload/image-1509e7d9-2107-4e05-9d4a-f0d94e681ffb.jpg) **author\_profile.html (my\_first\_app/views):** ![](https://static.platzi.com/media/user_upload/image-06f6c99d-d135-4aec-b9c6-ad6d0545577a.jpg)
Me parece que esta clase de URL fue muy resumida y muy rápida. Hubiese sido mejor que empiece con la creación de la URL de la homepage creándola desde my_first_project y luego si con la explicación de include urls en las app.
urls.py ```python from django.http import HttpResponsefrom django.urls import path from my\_first\_app.views import author\_profile\_show def my\_view(request, \*args, \*\*kwargs):    print(args)    print(kwargs)    return HttpResponse("") urlpatterns = \[    path("listado/", my\_view),    path("detalle/\<int:id>", my\_view),    path("marcas/\<str:brand>", my\_view),    path("author\_profile/\<int:id>", author\_profile\_show), ``` **view.py** ```python from django.shortcuts import renderfrom my\_first\_app.models import Car, Profile \# Create your views here.def my\_view(request):    car\_list = Car.objects.all()    context = {        "car\_list":car\_list    }    return render(request, "my\_first\_app/car\_list.html", context) def author\_profile\_show(request, id):    profile = Profile.objects.get(author\_id = id)    context = {        "profile":profile    }    return render(request, "my\_first\_app/author\_profile.html", context) ``` **author\_profile.py** ```html \\<html lang="en">\<head>    \<meta charset="UTF-8">    \<meta name="viewport" content="width=device-width, initial-scale=1.0">    \<title>Document\</title>\</head>\<body>    \<head>AUTHOR PROFILE\</head>    \<main>        \<article>            \<header>                \

{{ profile.author.name}}\

                \

Fecha de nacimiento: \<time>{{ profile.author.birth\_date }}\</time>\

            \</header>            \<footer>                \

{{ profile.biography }} \

                \                {{ profile.website }}            \            \</footer>        \</article>    \</main>\</body>\</html> ```
1. url app![](https://static.platzi.com/media/user_upload/image-ec2372b5-8232-43ef-bb3f-007ddddb2c7c.jpg) 2. url proyecto ![](https://static.platzi.com/media/user_upload/image-779af117-6cf9-4b38-b905-759ec67f2714.jpg) 3. vista autor ![](https://static.platzi.com/media/user_upload/image-3ef8fc04-7dd5-4dcb-b027-c6c3feb36b03.jpg) 4. html ![](https://static.platzi.com/media/user_upload/image-865b2f1b-d306-42bd-96ff-44d072f090e6.jpg) 5. resultado![](https://static.platzi.com/media/user_upload/image-8d09d7d7-26bf-4854-884a-0343afac9bb8.jpg)