在Django CreateView中保存反向外键

时间:2020-01-25 08:45:44

标签: django django-views

我有以下两种型号:

class Company(models.Model):
    ...
    contact_person = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name=_("Contact person"))
    ...
class Assignment(models.Model):
    ...
    company = models.ForeignKey('company.Company', null=True, blank=True,
                                on_delete=models.CASCADE, verbose_name=_("Company"))
    ...

我想根据当前登录用户在使用Django的company时自动填充CreateView字段。因为每个Company模型都与ForeignKeyUser关系。因此,我重写了form_valid方法,但是如何在此处为公司字段获取正确的值?

class AssignmentCreateView(generic.edit.CreateView):

    def form_valid(self, form):
        instance = form.save(commit=False)
        instance.company = self.request.user
        super(AssignmentCreateView, self).save(form)

1 个答案:

答案 0 :(得分:1)

mTableView.rowHeaderWidth = 0;