如何子类化Django CreateView

时间:2018-09-26 01:04:14

标签: python django django-models django-forms django-views

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

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()吗?

1 个答案:

答案 0 :(得分:1)

您只需要在通用视图的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