Django信号和表单is_valid

时间:2017-09-30 00:40:58

标签: django signals

此问题与this有关。我想保存与创建的信号相关的表单数据:

型号:

  class PatientInfo(models.Model):
     lastname = models.CharField('Last Name', max_length=200)
     ...

  class MedicalHistory(models.Model):
    patient = models.OneToOneField(PatientInfo, on_delete=models.CASCADE, primary_key=True)
    physician_name = models.CharField('Physician', max_length=200, null=True, blank=True)
    ...

  @receiver(post_save, sender=PatientInfo)
  def create_medical_history(sender, **kwargs):
     if kwargs.get('created', False):
     MedicalHistory.objects.create(patient=kwargs.get('instance'))

查看

class MedicalCreateView(CreateView):
    template_name = 'patient/medical_create.html'
    model = MedicalHistory
    form_class = MedicalForm
    success_url = '/'

    def post(self, request, pk):
      form = self.form_class(request.POST)
      if form.is_valid():
        patiente = form.save(commit=False)
        physician_name = form.cleaned_data['physician_name'] # do not delete
        patiente.save()
        messages.success(request, "%s is added to patient list" % physician_name )
        return redirect('index')
      else:
        print(form.errors)

上面的代码在我的MedicalHistory表中保存了两个条目,患者字段链接到Patient_info.id,而另一个是空的,但填充了表单数据。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

由于我的MedicalHistory模型已根据我的PatientInfo自动生成了自己的模型。我将数据填充到现有MedicalHistory ID的方法是更改​​:

class MedicalCreateView(CreateView)

class MedicalCreateView(UpdateView):

我删除了这个

def post(self, request, pk):

  form = self.form_class(request.POST)
   if form.is_valid():
     patiente = form.save(commit=False)
     physician_name = form.cleaned_data['physician_name'] # do not delete
     patiente.save()
     messages.success(request, "%s is added to patient list" % physician_name )
     return redirect('index')
   else:
     print(form.errors)