user8244361
user8244361

Reputation:

How to pass additional arguments to class view in django?

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 ?

Upvotes: 1

Views: 1585

Answers (2)

sudden_appearance
sudden_appearance

Reputation: 2197

Possible duplicate of URL-parameters and logic in django...

You can access your course_id via

self.kwargs['course_id']

Use it inside class-based view functions

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476503

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.

Upvotes: 1

Related Questions