gpt4 book ai didi

python - 我如何继承 Django CreateView

转载 作者:太空宇宙 更新时间:2023-11-04 04:31:50 25 4
gpt4 key购买 nike

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

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

关于python - 我如何继承 Django CreateView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52508541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com