Reputation: 41685
Suppose I have a url pattern
url(r'^/my_app/class/(?P<class_id>\d+)/$', my_class.my_class, name='my_class')
For a given url
http://example.com/my_app/class/3/
, I'd like to get class_id
.
I can do this with regex myself.
I am wondering if there's a utility function for this since Django is already doing this to resolve url to a view.
Upvotes: 5
Views: 2038
Reputation: 4159
There is an example of using resolve()
function in Django docs. Value of next
variable has HTTP url to be parsed with urlparse()
/ resolve()
:
https://docs.djangoproject.com/en/1.11/ref/urlresolvers/#resolve
from django.urls import resolve
from django.http import HttpResponseRedirect, Http404
from django.utils.six.moves.urllib.parse import urlparse
def myview(request):
next = request.META.get('HTTP_REFERER', None) or '/'
response = HttpResponseRedirect(next)
# modify the request and response as required, e.g. change locale
# and set corresponding locale cookie
view, args, kwargs = resolve(urlparse(next)[2])
kwargs['request'] = request
try:
view(*args, **kwargs)
except Http404:
return HttpResponseRedirect('/')
return response
Upvotes: 2
Reputation: 56
If you are using generic views or just views, you can do something like this:
class myView(View): # or UpdateView, CreateView, DeleteView
template_name = 'mytemplate.html'
def get(self, request, *args, **kwargs):
context = {}
class_id = self.kwargs['class_id']
# do something with your class_id
return render(request, self.template_name, context)
# same with the post method.
Upvotes: 2
Reputation: 19
Yes, you can do like this
def my_class(request, class_id):
# this class_id is the class_id in url
# do something;
Upvotes: 2