Reputation: 173
I am trying to pass date and id through url, but getting an error, I have passed just id before and I usually do it like this.
path('user_payment_menu/<int:pk>/',user_payment_menu, name='user_payment_menu'),
but now I want date to pass after int:pk/ but when I add date after a slash I am getting an error.
Upvotes: 4
Views: 6115
Reputation: 476594
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 %}
Upvotes: 13
Reputation: 676
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()])
Upvotes: 2