如何将参数传递给 django 通用视图
我想将一个数字传递到我的通用视图(DetailView)以获取一个对象 这是我的代码
Urlpattern
(r'^newreportview/(?P<number>\w+)/$', NewReportView.as_view()),
View Class
class NewReportView(DetailView):
template_name = "report/newreportview.html"
context_object_name = "newreportview"
def get_queryset(self):
task= get_object_or_404(MyTask,applicationnnumber=self.args[0])
return task
我猜这行错误消息中有问题
name = get_object_or_404(MyTask,applicationnnumber=self.args[0])
:
Exception Type: IndexError
Exception Value:
tuple index out of range
How should I pass 'number' to this generic view and get a Mytask 对象带有这个“数字”?
谢谢
I would like to pass a number to my generic view (DetailView) to get one object Here is my code
Urlpattern
(r'^newreportview/(?P<number>\w+)/
View Class
class NewReportView(DetailView):
template_name = "report/newreportview.html"
context_object_name = "newreportview"
def get_queryset(self):
task= get_object_or_404(MyTask,applicationnnumber=self.args[0])
return task
I guess something is wrong in this line
name = get_object_or_404(MyTask,applicationnnumber=self.args[0])
error message:
Exception Type: IndexError
Exception Value:
tuple index out of range
How should I pass 'number' to this generic view and get a Mytask object with this 'number'?
Thanks
, NewReportView.as_view()),
View Class
I guess something is wrong in this line
error message:
How should I pass 'number' to this generic view and get a Mytask object with this 'number'?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你已经错过了一般观点的全部要点。对于简单的 DetailView - 这是单个对象的视图 - 您只需在类中定义
model
和slug
属性:(您也可以轻松地传递这些属性三个作为 URL 定义中的参数,因此根本不需要创建子类。)
您没有获得
self.args
值的原因是您将参数作为 kwarg 传递,而不是一个参数。因此,self.kwargs['number']
会起作用,就像我在此处显示的修改后的 URL 一样。You have missed the entire point of generic views. For a simple DetailView - which is a view of a single object - you just define the
model
andslug
attributes in the class:(You could also just as easily have passed those three as parameters in the URL definition, so no need to make a subclass at all.)
The reason why you were getting no values for
self.args
is that you had passed your parameter as a kwarg, not an arg. Soself.kwargs['number']
would have worked, as would the revised URL I've shown here.