How to pass additional arguments to class view in django?

Viewed 385
def edit_course(request,course_id):
    course=Courses.objects.get(id=course_id)
    return render(request,"hod_template/edit_course_template.html",{"course":course,"id":course_id})

The code above shows a view in django that is defined as a function. I want to recreate the same view as a class based view in django but I couldn't pass in an additional argument such as course_id into the class based view as it shows an error. Can someone tell me how to recreate that above function into a class based view ?

2 Answers

You can make a DetailView with 'course_id' as pk_url_kwarg. An equivalent DetailView is:

from django.views.generic import DetailView

class EditCourseView(DetailView):
    model = Courses
    pk_url_kwarg = 'course_id'
    context_object_name = 'course'
    template_name = 'hod_template/edit_course_template.html'

Note: normally a Django model is given a singular name, so Course instead of Courses.

Related