Django,从url中提取kwargs

时间:2017-08-29 07:31:49

标签: django

假设我有一个网址格式

    var app = angular.module("myApp", []);
    app.controller("MyController", function($scope) {
        $scope.item = {
            "Item1": [{
                "title": "Item1",
                "choices": ["Egg", "burger", ]
            }],
            "Item2": [{
                "title": "Item2",
                "choices": ["Pizza", "Rice", ]
            }]
        };
 $scope.myFunc = function() {
$scope.myItem.choices=$scope.item[$scope.myItem.title][0].choices;
    };
        $scope.myItem = {
            title: null,
            choices: null
        };
    });

对于给定的网址

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <ul ng-app="myApp" ng-controller="MyController"> <select ng-model="myItem.title" ng-change="myFunc()" ng-options="value[0].title as key for (key , value) in item"> <option value="">Select Items</option> </select> <select ng-model="myItem.choice" ng-options="x for x in myItem.choices" > <option value="">Select choice</option> </select>{{myItem.choices}} </ul>,我想url(r'^/my_app/class/(?P<class_id>\d+)/$', my_class.my_class, name='my_class') 。 我自己可以用正则表达式做到这一点 我想知道是否有一个实用功能,因为Django已经这样​​做以解决网址的问题。

3 个答案:

答案 0 :(得分:1)

是的,你可以这样做

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

答案 1 :(得分:1)

在Django docs中有一个使用resolve()函数的例子。 next变量的值具有要使用urlparse() / resolve()解析的HTTP网址:

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

答案 2 :(得分: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.