2

I'm using Django 2.0

I have two modesl course and chapter

I want to pass course.pk in CreateView of chapter since chapter is related to course.

This is my urls.py

from django.urls import path

from courses.views import Courses, NewCourse, CourseView, NewChapter

app_name = 'course'
urlpatterns = [
    path('all', Courses.as_view(), name='list'),
    path('new', NewCourse.as_view(), name='new'),
    path('<pk>/detail', CourseView.as_view(), name='detail'),
    path('<course_id>/chapter/add', NewChapter.as_view(), name='new_chapter')
]

and NewChapter(CreateView)

class NewChapter(CreateView):
    template_name = 'courses/chapter/new_chapter.html'
    model = Chapter
    fields = ['name']

    def get_context_data(self, **kwargs):
        context = super(NewChapter, self).get_context_data(**kwargs)
        course = Course.objects.get(pk=kwargs['course_id'])
        if course is None:
            messages.error(self.request, 'Course not found')
            return reverse('course:list')

        return context

    def form_valid(self, form):
        form.instance.created_by = self.request.user
        form.instance.course = Course.objects.get(pk=self.kwargs['course_id'])
        form.save()

I also want to carry on validation if the Course with passed course_id exists or not. If it does not exists user will be redirected back otherwise he will be able to add chapter to it.

But it is giving error as

KeyError at /course/9080565f-76f4-480a-9446-10f88d1bdc8d/chapter/add

'course_id'

How to access parameters of path url in view?

1 Answer 1

2

You need to use self.kwargs, not kwargs.

course = Course.objects.get(pk=self.kwargs['course_id'])
Sign up to request clarification or add additional context in comments.

2 Comments

But, **kwargs is passed in get_context_data() so, it should work.
Well, since it didn't work, you should ask why. And the answer is that those are completely different things; the kwargs passed to that method are just normal method keyword arguments, nothing at all to do with the arguments captured from the URL.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.