Django中的CreateView有些麻烦

时间:2017-06-18 07:31:33

标签: python django django-class-based-views django-generic-views class-based-views

class Biochemical_analysis_of_blood(CreateView):
    model = BiochemicalAnalysisOfBlood
    form_class = BiochemicalAnalysisOfBloodForm
    template_name = "biochemical_analysis_of_blood.html"
    success_url = reverse_lazy("patients")

    def get_context_data(self, **kwargs):
        context = super(Biochemical_analysis_of_blood, self).get_context_data(**kwargs)
        patient = Patient.objects.get(id=1)
        context["patient"] = patient
        return context

    def post(self, request, *args, **kwargs):
        analysis = Analyzes()
        sid = transaction.savepoint()
        analysis.name = request.POST["name"]
        analysis.patient_id = Patient.objects.get(id=1)
        analysis.who_send = request.POST["who_send"]
        analysis.who_is_doctor = request.POST["who_is_doctor"]
        analysis.lab_user_id = Doctor.objects.get(id=request.POST["lab_user_id"])
        analysis.additional_lab_user = request.POST["lab_user_add"]
        analysis.date = '2017-06-18'
        analysis.type = 3
        analysis.date_analysis = '2017-06-18'
        analysis.save()
        return super(Biochemical_analysis_of_blood, self).post(request, *args, **kwargs)

我有下一个算法:

  1. 向用户呈现BiochemicalAnalysisOfBloodForm

  2. 当他填写字段并按下按钮“保存”时,我创建一个Analyzes()的新实例并以编程方式填充它,当我在post方法中调用super().post()时,将写入用户数据自动到模型BiochemicalAnalysisOfBlood?但我有下一个错误:

  3.   

    NOT NULL约束失败:   laboratory_biochemicalanalysisofblood.analysis_id

    我如何手动模式将模型添加到“分析”早期创建的Analyzes()实例的字段中?我不明白这个课程到底能找到所有机会的信息

2 个答案:

答案 0 :(得分:1)

算法的主要部分应该位于表单中,因为您要将analysis_id传递给正在保存的实例

class BiochemicalAnalysisOfBloodForm(ModelForm):
    def save(self, commit=True):
        analysis = Analyzes()
        sid = transaction.savepoint()
        analysis.name = self.data["name"]
        analysis.patient_id = Patient.objects.get(id=1)
        analysis.who_send = self.data["who_send"]
        analysis.who_is_doctor = self.data["who_is_doctor"]
        analysis.lab_user_id = Doctor.objects.get(id=self.data["lab_user_id"])
        analysis.additional_lab_user = self.data["lab_user_add"]
        analysis.date = '2017-06-18'
        analysis.type = 3
        analysis.date_analysis = '2017-06-18'
        analysis.save()
        # Your analysis is created, attach it to the form instance object
        self.instance.analysis_id = analysis.id
        return super().save(commit)

答案 1 :(得分:0)

在执行super()。post之前,您可以修改request.POST数据以包含您的分析ID:

request.POST['analysis_id'] = analysis.id

这可能会有所帮助。

另请注意,如果表单验证在super()。post中失败,您仍然会创建一个可能没用的Analysis对象。您可以使用覆盖CreateView的form_invalid方法来处理此问题。