Skip to main content
 首页 » 编程设计

python之我如何继承 Django CreateView

2024年12月31日27Leo_wl

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

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 个外键(candidate 和 note_by)

在表单上,​​我将只显示字段“job_note” 'candidate' 和 'note_by' 字段将由 View 填充

class CreateNoteView(CreateView): 
 
    template_name = 'candidates/create_note.html'  
    form_class = CreateNoteForm     
    success_url = reverse_lazy('staff_main') 

我被告知可以使用通用CreateView,但我必须“子类”'get_form()' 方法和以下内容:

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

我查看了 CreateView 类中默认的“get_form()”方法,它有:

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

我究竟如何“子类”并添加

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

到“get_form”方法,我在...的部分放了什么:

form = CreateNoteForm(...); 

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

请您参考如下方法:

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

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