Django how to add a form to a DetailView with FormMixin

Solution 1:

Try to change the order between DetailView and FormMixin in ProjectNotesDetailView then implement the post method (enabled by the `FormMixin):

class ProjectNotesDetailView(FormMixin, DetailView):
    model = ProjectNotes
    id = ProjectNotes.objects.only('id')
    template_name = 'company_accounts/project_note_detail.html'
    comments = ProjectNotes.comments
    form_class = NoteCommentForm

    def form_valid(self, form):
        projectnote = get_object_or_404(ProjectNotes, id=self.kwargs.get('pk'))
        comment = form.save(commit=False)
        comment.projectnote = projectnote
        comment.save()
        return super().form_valid(form)

    def get_success_url(self):
        return reverse('project_detail', args=[self.kwargs.get('pk')])



    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return HttpResponseForbidden()
        self.object = self.get_object()
        form = self.get_form()
        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

Check how to use formmixin with detailview (documentation).