models.py
class Employee(models.Model):
name = models.CharField(max_length=100)
company = models.ForeignKey(Company, null=True, on_delete=models.SET_NULL, related_name='company')
views.py
class Employee(CreateView):
fields = ('name','company')
model = models.Employee
def form_valid(self, form):
self.object = form.save(commit=False)
comp_name = self.request.POST.get("company", "")
shop_id = ""
for word in dept_name.split(" "):
shop_id += word[:1]
self.object.nik = shop_id[-3:]
self.object.save()
return super(ModelFormMixin, self).form_valid(form)
iam尝试从我的代码self.request.POST.get("company", "")
获取ForeignKey的值是公司的返回id
,我需要返回company.name
。怎么做?...
答案 0 :(得分:0)
你不应该访问request.POST
;表单的重点是它将发布的数据转换为正确的格式,在本例中为ForeignKey。
此处,由于form.save
,公司已存储在对象上;你应该在那里访问它:
self.object = form.save(commit=False)
comp_name = self.object.company.name