简体   繁体   中英

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?

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM