How to detailview pk in post method in DetailView? (Django)

Question:

In my detailView I have 2 methods get_context_data and post. In get_context_data I can get the detailView pk with self.object.pk but how can I get it in the post method?

[ updated ]

here is the view

class Class_detailView(LoginRequiredMixin, DetailView):
    login_url = '/'
    model = Class
    template_name = "attendance/content/teacher/class_detail.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['attendance_form'] = AttendanceForm(current_class_pk=self.object.pk) # pass data to form via kwargs 
        return context

    def post(self, request, *args, **kwargs):
        if request.method == "POST":
            attendance_form = AttendanceForm(request.POST)
            if attendance_form.is_valid():
                attendance_form.instance.teacher = self.request.user
                attendance_form.save()
                return redirect('class-detail', pk=self.kwargs.get('pk'))

form

class AttendanceForm(forms.ModelForm):
    class Meta:
        model = Attendance
        fields = ['student',]

    def __init__(self, *args, **kwargs):
        current_class_pk = kwargs.pop('current_class_pk')
        super(AttendanceForm, self).__init__(*args, **kwargs)
        current_student = Class.objects.get(id=current_class_pk)
        self.fields['student'].queryset = current_student.student

I want to get the pk and pass it to the form when the post request is called.
How can I do it?

Asked By: Carlos

||

Answers:

did you try this:

def post(self, request, *args, **kwargs):
    if request.method == "POST":
        attendance_form = AttendanceForm(request.POST, current_class_pk=self.kwargs.get('pk'))
        if attendance_form.is_valid():
            attendance_form.instance.teacher = self.request.user
            attendance_form.save()
            return redirect('class-detail', pk=self.kwargs.get('pk'))
Answered By: Diego Puente
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.