How to pass date and id through url in django

Solution 1:

Probably the easiest way to define a date is with a custom path converter. You can implement this with:

# app_name/converters.py

class DateConverter:
    regex = '\d{4}-\d{1,2}-\d{1,2}'
    format = '%Y-%m-%d'

    def to_python(self, value):
        return datetime.strptime(value, self.format).date()

    def to_url(self, value):
        return value.strftime(self.format)

Then you can register the format and use the <date:…> path converter:

# app_name/urls.py

from django.urls import path, register_converter
from app_name.converters import DateConverter
from app_name.views import user_payment_menu

register_converter(DateConverter, 'date')

urlpatterns = [
    path('user_payment_menu/<int:pk>/<date:mydate>/',user_payment_menu, name='user_payment_menu'),

then in the view you define an extra attribute that will contain the date as a date object:

# app_name/views.py

def user_payment_menu(request, pk, mydate):
    # …

You can use a date object when generating a URL, for example with:

{% url 'user_payment_menu' pk=somepk mydate=somedate %}

Solution 2:

It's easy:

path('user_payment_menu/<int:pk>/<str:date>',user_payment_menu, name='user_payment_menu'),

and you can use it like that:

reverse('user_payment_menu', args=[1, str(date.today()])