当我创建带有外键字段的新对象时,模板中是否有办法在创建表单上的模板中获取外键对象字段?每当我创建新便笺时,我都希望拥有:“将新便笺添加到{{申请人.full_name}}”
class Applicant(models.Model):
first_name = models.CharField(max_length=128,blank=False, verbose_name="First Name")
middle_name = models.CharField(max_length=128,blank=True, verbose_name="Middle Name")
last_name = models.CharField(max_length=128,blank=False, verbose_name="Last Name")
@property
def full_name(self):
"Returns the applicant's full name."
return '%s %s %s' % (self.first_name, self.middle_name, self.last_name)
class Note(models.Model):
applicant = models.ForeignKey(Applicant, related_name='notes', on_delete=models.CASCADE)
description = models.TextField(blank=True)
)
(已更新)这是视图:
class NoteCreate(CreateView):
model = Note
form_class = forms.NoteForm
template_name = 'careers/add_note.html'
def form_valid(self, form):
applicant_pk = self.kwargs['pk']
applicant = Applicant.objects.get(pk=applicant_pk)
self.object = form.save(commit=False)
self.object.applicant = applicant
self.object.save()
return super(NoteCreate, self).form_valid(form)