Django.fun

how can I get the id of the object from Subjects model?

I want to associate a post for that certain object in the subject's model but I can't figure it out (error in views.py). Your help is appreciated for a beginner like me.

models.py

class Subjects(models.Model):
    title = models.CharField(max_length=200)
    slug = AutoSlugField(populate_from=['title'], max_length=250, unique=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return f"{self.title}"

    @property
    def posts(self):
        return Post.objects.filter(subject=self)


class Post(models.Model):
    subject = models.ForeignKey(
        Subjects, on_delete=models.CASCADE, related_name='subject_model')
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    body = RichTextField(blank=True, null=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

views.py

class PostCreateView(LoginRequiredMixin, CreateView):
template_name = 'post/post_create.html'
model = Post
fields = ['body']
success_url = '/'

def form_valid(self, form):
    form.instance.author = self.request.user
    form.instance.subject_id = self.kwargs['id'] # error here
    form.save()
    return super(PostCreateView, self).form_valid(form)

urls.py

urlpatterns = [
    path('', views.CourseList.as_view(), name='course_list'),
    path('create_subject', views.SubjectCreateView.as_view(), name='create_subject'),

    # register
    path('register/', views.register, name='register'),

    # detailview
    path('<int:id>/', views.SubjectDetailView.as_view(), name='subject-detail'),

    # post create view
    path('post/new/',
         views.PostCreateView.as_view(), name='post-create')

]

error KeyError at /post/new/ 'id'

Answers: 0