Вопрос

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

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top