How to pass parameters to django generic views

限于喜欢 提交于 2020-01-13 07:16:49

问题


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+)/$', 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

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


回答1:


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 and slug attributes in the class:

(r'^newreportview/(\d+)/$', NewReportView.as_view()),  

class NewReportView(DetailView):
    template_name = "report/newreportview.html"
    model = MyTask
    slug = 'applicationnnumber'

(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. So self.kwargs['number'] would have worked, as would the revised URL I've shown here.



来源:https://stackoverflow.com/questions/8458412/how-to-pass-parameters-to-django-generic-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!