如何从url获取变量以形成方法 - 保存?

时间:2017-06-18 18:15:46

标签: python django django-models django-forms django-generic-views

我有id

的urlpattern
...
url(r'^3/(?P<id>[-\w]+)', Biochemical_analysis_of_blood.as_view(),\
    name='biochemical_analysis_view'),
...

views.py

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)
        context["patient"] = Patient.objects.get(id=self.kwargs['id'])
        context["caption"] = 'Біохімічний аналіз крові'
        context["new"] = True
        return context

forms.py

class SaveForms():
    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 = self.data["date"]
        analysis.type = 3
        analysis.date_analysis = self.data["date_analysis"]
        analysis.save()
        # Your analysis is created, attach it to the form instance object
        self.instance.analysis_id = analysis.id
        return super().save(commit)

我如何获得变量&#34; id&#34;从网址到表格的方法 - 保存? class SaveForms将被其他forms.models类所包含,因为它们都必须具有相同的save方法。

...
    analysis.patient_id = Patient.objects.get(id=1)
...

相反&#34; 1&#34;我必须使用&#34; id&#34;来自网址...谁能帮助我,拜托?

class BiochemicalAnalysisOfBloodForm(SaveForms, forms.ModelForm):
...

1 个答案:

答案 0 :(得分:1)

您可以在表单中访问请求数据,请查看以下答案:

How do I access the request object or any other variable in a form's clean() method?

取代request.user对象取request.path。