Search code examples
pythondjangodjango-modelsdjango-formsdjango-generic-views

how get a variable from url to form's method - save?


I have urlpattern with id

...
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)

How I can get a variable "id" from url to form's method - save? class SaveForms will be inherethed by other forms.models classes because they all must have same save method.

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

Instead "1" I must use "id" from url...Who can help me, please?

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

Solution

  • You can acces the request data in your form, check this answer:

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

    Instead of the request.user object take request.path.