django optional path parameter

  1. Define the URL pattern in your Django application's urls.py file.
from django.urls import path
from . import views

urlpatterns = [
    path('example/<str:optional_param>/', views.example_view),
]
  1. Create a view function in the associated views.py file.
from django.shortcuts import render

def example_view(request, optional_param=None):
    # Your view logic here
    context = {'optional_param': optional_param}
    return render(request, 'example_template.html', context)
  1. Handle the optional parameter in your view function. In this example, the optional parameter is captured as optional_param and passed to the template context.

  2. Optionally, create an HTML template to render the response. In this example, the template might be named example_template.html.

<!DOCTYPE html>
<html>
<head>
    <title>Example Template</title>
</head>
<body>
    <h1>Optional Parameter Example</h1>
    {% if optional_param %}
        <p>Optional Parameter: {{ optional_param }}</p>
    {% else %}
        <p>No optional parameter provided.</p>
    {% endif %}
</body>
</html>

Note: The optional_param variable is used in the template to display the optional parameter if it is provided, or indicate that no optional parameter was provided if it's None.