Home > Net >  django: reverse() fails when passing extra options to view function
django: reverse() fails when passing extra options to view function

Time:07-08

I'm struggling with an annoying error with Django, I'm trying a reverse() passing metadata as a Python dictionary (I'm following the documentation but it does't work, can you help me figure out what I'm missing? )

This is my urlpattern (as you can see I'm passing extra options to my view function, as described in the docs):

from django.urls import path
from . import views

urlpatterns = [
    ...,
    path("items/<int:item_id>", views.item_page, { 'message': None }, name="item page")
]

On my views.item_page function I have this: as

...

reversed_url = reverse("item page", kwargs={'item_id': item_id, 'message': 'hello'} )

return HttpResponseRedirect(reversed_url)

I'm getting this kind of error:

Django Version:     4.0.4
Exception Type:     NoReverseMatch
Exception Value:    Reverse for 'item page' with keyword arguments '{'item_id': 2, 'message': 'hello'}' not found. 1 pattern(s) tried: ['items/(?P<item_id>[0-9] )\\Z']

It's like it doesn't accept the "message" argument when reversing.

CodePudding user response:

reverse will accept only the arguments those exist in the urlpattern in your pattern there is no message **if you want to send messages ** you can use the messages module in django

from django.contrib import messages 

# in View
messages.success(request, 'Hello')
...

See the Docs for Sending messages

CodePudding user response:

Another way to pass somewhat structured extra information to the next view is to populate its request.GET with a Querydict. Something like

qd = QueryDict( mutable=True)
qd['whatever'] = 'whatever' # populate it as you wish next view's request.GET to be
...
url = reverse('myapp:wherever', kwargs={ ...} ) # kwargs as defined in urls.py
return HttpResponseRedirect( url   '?'   qd.urlencode() )
  • Related