保存表单时为什么会出现错误?

时间:2019-08-22 15:19:38

标签: python django django-forms

有两种型号

模型1

class Work(models.Model):

    employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='employee_projects')
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='project_work')
    ...
    responsibility = models.TextField("employee work responsibility", blank=True)

模型2

class Project(models.Model):
    name = models.CharField("project name", max_length=64)
    description = models.TextField("project description")
    technologies = models.ManyToManyField(
        Technology, verbose_name="technologies used on the project")

我使用modeinlineformset创建新对象

forms.py

class ProjectForm(forms.ModelForm):
    class Meta:
        model = Project
        fields = ['name', 'description', 'technologies']


ProjectFormSet = inlineformset_factory(Project, Work,
                                       fields=['responsibility', 'start_year', 'start_month', 'end_year', 'end_month'],
                                       extra=1)

和我的观点。py

class WorkCreateView(AuthorizedMixin, CreateView):
    """
    Create new course instances
    """
    model = Project
    form_class = ProjectForm
    template_name = 'work_edit.html'

    def get(self, request, *args, **kwargs):

        ....

    def post(self, request, *args, **kwargs):
        self.object = None
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        project_form = ProjectFormSet(self.request.POST)
        if form.is_valid() and project_form.is_valid():
            return self.form_valid(form, project_form)
        else:
            return self.form_invalid(form, project_form)

    def form_valid(self, form, project_form):
        self.object = form.save()
        project_form.instance = self.object
        project_form.save(commit=False)
        project_form.instance.employee = Employee.objects.get(pk=self.kwargs['pk'])
        project_form.save()
        return redirect('{}#experience'.format(reverse('profile', kwargs={'pk': self.kwargs['pk']})))

    def form_invalid(self, form, project_form):
        ...

但是出现错误

null value in column "employee_id" violates not-null constraint

我知道此错误的含义,但是如果我将当前employee的值分配给instance.employee,我不明白为什么会发生这种情况。

UPD

我试图更改视图

def form_valid(self, form, project_form):
    self.object = form.save()
    instances = project_form.save(commit=False)
    for instance in instances:
        instance.employee = Employee.objects.get(pk=self.kwargs['pk'])
        instance.save()
    return redirect('{}#experience'.format(reverse('profile', kwargs={'pk': self.kwargs['pk']})))

但是出现新错误

save() prohibited to prevent data loss due to unsaved related object 'project'.

0 个答案:

没有答案