我有一个模型,为此,我想将一些参数传递给表单。
该模型是:

class CandidateNote(models.Model):
    candidate   = models.ForeignKey(CandProfile, on_delete=models.CASCADE, related_name='candidatenotes_cand')
    note_by     = models.ForeignKey(BaseUser, null=True, on_delete=models.SET_NULL, related_name='candidatenotes_user')
    job_note    = models.TextField(max_length=3000)
    date_added  = models.DateTimeField(auto_now_add=True)


如您所见,模型有2个外键(候选和note_by)

在表格上,我只会显示字段“ job_note
视图将填充“ candidate”和“ note_by”字段

class CreateNoteView(CreateView):

    template_name = 'candidates/create_note.html'
    form_class = CreateNoteForm
    success_url = reverse_lazy('staff_main')


我被指示可以使用通用CreateView,但是我将必须使用“ subclass”和“ get_form()”方法,并坚持以下几点:

form = CreateNoteForm(...);
form.instance.candidate = self.object;
form.instance.note_by = self.request.user;
form.save()


我在get_form()类中查看了默认的'CreateView'方法,它具有:

def get_form(self, form_class=None):
    """Return an instance of the form to be used in this view."""
    if form_class is None:
        form_class = self.get_form_class()
    return form_class(**self.get_form_kwargs())


我到底如何“ subclass”并继续前进

    form = CreateNoteForm(...);
    form.instance.candidate = self.object;
    form.instance.note_by = self.request.user;
    form.save()


到'get_form'方法,以及我在...的...部分中输入什么:

form = CreateNoteForm(...);


在我看来,我现在真的应该form.save()吗?

最佳答案

您只需要在通用视图的super方法上调用get_form命令,如下所示:

class CreateNoteView(CreateView):
    ...
    def get_form(self, form_class=None):
        # Python 2.7-style super command:
        form = super(CreateNoteView, self).get_form(form_class)

        # If using Python 3, you would do this instead:
        # form = super().get_form(form_class)

        # begin the code that you wish to tack on:
        form.instance.candidate = self.object;
        form.instance.note_by = self.request.user;
        form.save()

        # Return the form variable, just like the parent class's get_form method:
        return form

10-04 10:28