Anuj TBE
Anuj TBE

Reputation: 9806

access path url parameter in view in Django

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?

Upvotes: 2

Views: 1805

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599956

You need to use self.kwargs, not kwargs.

course = Course.objects.get(pk=self.kwargs['course_id'])

Upvotes: 2

Related Questions