Previously we have been accessing kwargs
in Django templates with {{view.kwargs.kwarh_name}}
.
However, it has been to my surprise that this is not working in my django 3.2.4 Has it been removed, is there any issue with the line above?
Note: Kwargs here I mean something like below: Given a function as below:
def GetSomething(request, code):
return render(request, "some template here")
Now, the urlpatterns would be something like,
import GetSomething from .views
app_name = "some_app_name_here"
urlpattern = [
path("link/<int:code>/", GetSomething, name="some_cool_name") #http:localhost/link/12345/
]
Now in HTML/Django templates or Jinja2(whichever you use), accessing this code would be via {{ view.kwargs.code }}
But it so happens that this is not working for me in Django 3.2, any reasons??
Hope I was very clear!
CodePudding user response:
The get_context_data method of class based views adds the view to the context as view. If you have a function based view, it will not be added to the context automatically. This is not related to Django versions 3.2.4
So either use a class based view or use a function based view and pass the kwargs to the template through the context variable.
def GetSomething(request, code):
context = {
#some values here
'code':code,
}
return render(request, "some template here", context)
Then you can access your context variables in the template directly.
{{code}}