16

在 django 文档中,url 函数是这样的

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

我有这个

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

这是我的看法

class myview(TemplateView):

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

我收到这个错误

url() got an unexpected keyword argument 'model'
4

3 回答 3

19

您正在尝试将model关键字参数传递给url()函数;你需要传入一个kwargs参数(它需要一个字典):

url(r'^download/template/(?P<object_id>\d+)/$', views.myview().myfunction, 
    kwargs=dict(model=models.userModel), name="sample")
于 2012-12-03T07:33:05.320 回答
8

这:

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

应该:

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

查看文档

您当前的实现不是线程安全的。例如:

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"),
)

你会期望它打印 'Foo None ' 吗?请小心,因为实例是跨请求共享的:

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

因此,当它不是线程安全的时,您不能假设它在请求开始时会处于干净状态——这与使用 as_view() 时不同。

于 2012-12-03T07:31:30.110 回答
0

我相信如果你在你的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
于 2013-12-27T16:10:27.890 回答