Django 中 CreateView 的一些问题

some troubles with CreateView in the Django

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. 当他填写字段并按下按钮时 "save" 我创建了一个 Analyzes() 的新实例并以编程方式填写它,当在 post 方法中我调用 super().post() 那么用户数据会自动写入模型 BiochemicalAnalysisOfBlood 吗?但是我有下一个错误:

NOT NULL constraint failed: laboratory_biochemicalanalysisofblood.analysis_id

如何在手动模式下将 Analyzes() 的早期创建实例添加到字段 "analysis" 的模型中?我不明白这个 class 到底在哪里我可以找到关于它所有机会的信息

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

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

可能会有帮助。

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

您的算法的主要部分应该位于您的表单中,因为您想将 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)