2017-08-29 89 views
3

提取kwargs假設我有一個URL模式Django的,從網址

url(r'^/my_app/class/(?P<class_id>\d+)/$', my_class.my_class, name='my_class') 

對於給定的URL

http://example.com/my_app/class/3/,我想獲得class_id。 我可以用自己的正則表達式來做到這一點。
我想知道是否有一個實用的功能,因爲Django已經這樣​​做了解決url到視圖。

+0

怎麼樣django.urls.resolve()https://docs.djangoproject.com/en/1.11/ref/urlresolvers/#resolve –

回答

1

有一個在Django文檔使用resolve()函數的例子。 next變量的值HTTP URL與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 
1

是的,你可以這樣做

def my_class(request, class_id): 
    # this class_id is the class_id in url 
    # do something; 
0

如果您正在使用通用視圖或只是意見,你可以這樣做:

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.