forms.ModelForm不保存ManyToMany字段

时间:2016-07-19 02:18:43

标签: python django django-models django-forms

我正在处理表单(forms.ModelForm),当我在模型中创建表单时,我有一点不方便。我的情况如跟在我的models.py文件中:

我有CorporalSegment型号:

class CorporalSegment(models.Model):
    SEGMENTO_HOMBRO = 'Hombro'
    SEGMENTO_CODO = 'Codo'
    SEGMENTO_ANTEBRAZO = 'Antebrazo'
    SEGMENTO_MANO = 'Mano'

    SEGMENT_CHOICES = (
        (SEGMENTO_HOMBRO, u'Hombro'),
        (SEGMENTO_CODO, u'Codo'),
        (SEGMENTO_ANTEBRAZO, u'Antebrazo'),
        (SEGMENTO_MANO, u'Mano'),
    )

    corporal_segment = models.CharField(
        max_length=12,
        choices=SEGMENT_CHOICES,
        blank=False,
    )

    class Meta:
        verbose_name_plural = 'Segmentos Corporales'

    def __str__(self):
        return "%s" % self.corporal_segment

我有Movement型号

class Movements(models.Model):
    name = models.CharField(
        max_length=255,
        verbose_name='Movimiento'
    )
    class Meta:
        verbose_name_plural = 'Movimientos'

    def __str__(self):
        return "%s" % self.name

我有Metric模型

class Metrics(models.Model):
    name = models.CharField(
        max_length=255,
        blank=True,
        verbose_name='Nombre'
    )
    value = models.DecimalField(
        max_digits = 5,
        decimal_places = 3,
        verbose_name = 'Valor',
        null = True,
        blank = True
    )

    class Meta:
        verbose_name = 'Métrica'

    def __str__(self):
        return "{},{}".format(self.name, self.value)

我的目的是在一种形式下,我可以保存CorporalSegmentMovementMetric模型的多个值(实例),由于这个原因,我有{{1这种方式的模型:

PatientMonitoring

我的class PatientMonitoring(models.Model): patient = models.ForeignKey(...) medical = models.ForeignKey(...) # My fields pointing to my previous models with many to many relationship corporal_segment = models.ManyToManyField(CorporalSegment, verbose_name='Segmentos Corporales') movement = models.ManyToManyField(Movements, verbose_name='Movimientos') metrics = models.ManyToManyField(Metrics, verbose_name='Métricas', ) class Meta: verbose_name = 'Monitoreo del paciente' def __str__(self): return "%s" % self.patient 文件

views.py

我的class PatientMonitoringCreate(CreateView): model = PatientMonitoring form_class = PatientMonitoringForm success_url = reverse_lazy('patientmonitoring:list') class PatientMonitoringUpdate(UpdateView): model = PatientMonitoring form_class = PatientMonitoringForm success_url = reverse_lazy('patientmonitoring:list') 就是这样:

forms.py

我的模板from django import forms from .models import PatientMonitoring from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit class PatientMonitoringForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(PatientMonitoringForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.add_input(Submit('submit', u'Save')) # I think so that here is my problem ... def save(self, commit=True): patient_monitoring = super(PatientMonitoringForm, self).save(commit=False) patient = self.cleaned_data['patient'] if commit: patient_monitoring.save() return patient_monitoring class Meta: model = PatientMonitoring fields = ['patient', 'medical','corporal_segment','movement','metrics'] 是:

patientmonitoring_form.html

当我想以各自的形式保存{% extends 'base.html' %} {% load crispy_forms_tags %} {% block title %}Crear Registro de Monitoreo de Paciente{% endblock %} {% block content %} <div> {% crispy form %} {% csrf_token %} </div> {% endblock %} 个实例时,表单中的PatientMonitoring(Segmentos Corporales)corporal_segment(Movimientos)和movement(Metricas)字段,它们的值不保存在表格中(红色方块),但保存另一个字段(不是红色方块)

enter image description here

这种行为对我来说很奇怪,因为通过Django管理表单,可以保存metrics实例及其所有属性。

PatientMonitoring save文件的PatientMonitoringForm格式forms.py方法保存时,我会忽略哪些内容?

1 个答案:

答案 0 :(得分:6)

https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method

使用commit = False时,必须调用save_m2m()

m2m关系需要首先保存父对象,而不是使用commit = False进行保存。