How to make multiple urls in django?

Viewed 23

Learning django, can't create multithreaded url

How to display, for example, the brand of an audi car by url 127.0.0.1:8000/cars_brand/audi/Audi_TTS ?

Now it says None

I don't know what else to add here, but stackoverflow doesn't skip my question for the reason: It looks like your post is mostly code; please add some more details.

views

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

cars_brand_dict = {
    "audi": ["Audi_RS_2_Avant", "Audi_A8_W12", "Audi_TTS"],
    "bmw": ["BMW_M135i_xDrive", "BMW_M240i_xDrive_Coupe", "BMW_M3_Competition"],
    "volkswagen": ["Volkswagen_Caddy","Volkswagen_Multivan","Volkswagen_Crafter_Pritsche"],
}


cars_model_dict = {
"audi_dict" :{
    "Audi_RS_2_Avant": "ссылочка Audi_RS_2_Avant",
    "Audi_A8_W12": "ссылочка на Audi_A8_W12",
    "Audi_TTS": "ссылочка на Audi_TTS",
},

"bmw_dict" :{
    "BMW_M135i_xDrive": "ссылочка на BMW_M135i_xDrive",
    "BMW_M240i_xDrive_Coupe": "ссылочка на BMW_M240i_xDrive_Coupe",
    "BMW_M3_Competition": "ссылочка на BMW_M3_Competition",
},

"volkswagen_dict" :{
    "Volkswagen_Caddy": "ссылочка на Volkswagen_Caddy",
    "Volkswagen_Multivan": "ссылочка на Volkswagen_Multivan",
    "Volkswagen_Crafter_Pritsche": "ссылочка на Volkswagen_Crafter_Pritsche",
}
}


def get_info_about_car_brand(request, car_brand):
  description = cars_brand_dict.get(car_brand, None)
  return HttpResponse(description)

def get_info_about_car_model(request, car_brand, car_model):
  description = cars_model_dict.get(car_model)
  return HttpResponse(description)

default urls

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('cars_brand/', include("car_store.urls")),
]

my urls

from django.urls import path
from . import views

urlpatterns = [
    # path('', admin.site.urls),
    path('<car_brand>', views.get_info_about_car_brand),
    path('<car_brand>/<car_model>', views.get_info_about_car_model),
]
1 Answers

Just add slug <slug:{argument_name}> to the URLs, that seems to always work

And if you put a car_model=None in the View's arguments, you can point both URLs to the same View:

urlpatterns = [
    # path('', admin.site.urls),
    path('<slug:car_brand>', views.get_info_about_car),
    path('<slug:car_brand>/<slug:car_model>', views.get_info_about_car),

]
def get_info_about_car(request, car_brand, car_model=None):
  print('request', request)
  print('car_brand', car_brand)
  print('car_model', car_model)

  if car_model:
    description = cars_model_dict.get(car_model)
  else:
    description = cars_brand_dict.get(car_brand, None)
  return HttpResponse(description)
Related