为什么我不能将表单保存到我的数据库中?许多人,django

时间:2016-02-24 19:46:51

标签: mysql django forms many-to-many modelform

我有一个问题。我的表单有一个字段(多对多),此字段映射到m2m表,其中包含属性id_academic_degree id_employee和许可证。当我尝试保存它时,django会显示如下错误

无法在指定中间模型的ManyToManyField上设置值。使用employees.EmployeeAcademicDegree的经理。

查看

CreateEmployee(CreateView):
    model = Employee
    form_class = EmployeeForm
    template_name = 'CreateEmployee.html'

@transaction.atomic
def form_valid(self, form):
    form.save()
    form.save_m2m()
    messages.success(self.request, 'El Empleado fue guardado Exitosamente.')
    return HttpResponseRedirect(self.get_success_url())

def get_success_url(self):
    return reverse('physicians:CreatePerson',)

我的模特

class Employee(models.Model):
    person = models.OneToOneField(Person)
    region = models.ForeignKey(Region, db_column='id_region')
    academic_degrees = models.ManyToManyField(AcademicDegree, 
                       through='EmployeeAcademicDegree', blank=True)
    active = models.NullBooleanField()
    rfc = models.CharField(max_length=15, blank=True, null=True)
    shift_start = models.TimeField(blank=True, null=True)
    shift_end = models.TimeField(blank=True, null=True)
    history = HistoricalRecords()  # Always leave at the end.

    class Meta:
        db_table = 'employee'

    def __str__(self):
        return self.person.full_name

    def __unicode__(self):
        return self.person.full_name

class EmployeeAcademicDegree(models.Model):
    employee = models.ForeignKey(Employee, db_column='id_employee')
    academic_degree = models.ForeignKey(AcademicDegree,
                                        db_column='id_academic_degree')
    license = models.CharField(max_length=15, blank=True, null=True)
    history = HistoricalRecords()  # Always leave at the end.

    class Meta:
        db_table = 'employee_academic_degree'

    def __str__(self):
        return unicode(self.academic_degree)

    def __unicode__(self):
        return unicode(self.academic_degree)

表格如下

Employee
  id
  id_person
  id_region
  active(boolean)
  rfc
  shift_start
  shift_end

employee_academic_degrees
  id_employee_academic_degrees
  id_employee(FK)
  id_academic_degree(FK)
  license

我想我需要首先保存关系然后保存整个对象(但我不知道如何保存许可证,因为表单没有显示任何字段来填写许可证)

0 个答案:

没有答案