简体   繁体   English

如何在django中传递URL中的kwargs

[英]How can I pass kwargs in URL in django

In the django doc the url function is like this 在django doc中,url函数是这样的

url(regex, view, kwargs=None, name=None, prefix='')

I have this 我有这个

url(r'^download/template/(?P<object_id>\d+)/$', views.myview().myfunction,model=models.userModel, name="sample")

This is my view 这是我的观点

class myview(TemplateView):

    def myfunction(self,request, object_id, **kwargs):
        model = kwargs['model']

I get this error 我收到这个错误

url() got an unexpected keyword argument 'model'

You are trying to pass in a model keyword argument to the url() function; 您正尝试将model关键字参数传递给url()函数; you need to pass in a kwargs argument instead (it takes a dictionary): 你需要传入一个kwargs参数(它需要一个字典):

url(r'^download/template/(?P<object_id>\d+)/$', views.myview().myfunction, 
    kwargs=dict(model=models.userModel), name="sample")

This: 这个:

url(r'^download/template/(?P<object_id>\d+)/$', views.myview().myfunction,model=models.userModel, name="sample")

Should be: 应该:

url(r'^download/template/(?P<object_id>\d+)/$', views.myview.as_view(model=models.userModel), name="sample")

See docs 查看文档

Your current implementation is not thread safe. 您当前的实现不是线程安全的。 For example: 例如:

from django import http
from django.contrib.auth.models import User
from django.views import generic


class YourView(generic.TemplateView):
    def __init__(self):
        self.foo = None

    def your_func(self, request, object_id, **kwargs):
        print 'Foo', self.foo
        self.foo = 'bar'
        return http.HttpResponse('foo')



urlpatterns = patterns('test_app.views',
    url(r'^download/template/(?P<object_id>\d+)/$', YourView().your_func,
        kwargs=dict(model=User), name="sample"),
)

Would you expect it to print 'Foo None ' ? 你期望它打印'Foo None '吗? Well be careful cause the instance is shared across requests: 请小心,因为实例在请求之间共享:

Django version 1.4.2, using settings 'django_test.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Foo None
[03/Dec/2012 08:14:31] "GET /test_app/download/template/3/ HTTP/1.1" 200 3
Foo bar
[03/Dec/2012 08:14:32] "GET /test_app/download/template/3/ HTTP/1.1" 200 3

So, when it's not thread safe, you can't assume that it will be in a clean state when the request starts - unlike when using as_view(). 因此,当它不是线程安全时,您不能假设它在请求开始时将处于干净状态 - 与使用as_view()时不同。

I believe you would have the same functionality (and avoid threading issues) if you did this in your views.py 如果您在views.py此操作,我相信您将具有相同的功能(并避免线程问题)

from django.views.generic import TemplateView
from .models import userModel

class myview(TemplateView):
    def myfunction(self, request, object_id, *args, **kwargs):
        model = userModel
        # ... Do something with it

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM