在 Django 的 POST 数据中传递值和表单

Tim*_* B. 3 python django

当我在 HTML 中呈现表单时,我使用这个视图。患者 ID 用于表示签入的患者以及姓名显示等。

def Checkin(request, patient_id):
    patient = get_object_or_404(PatientInfo, pk=patient_id)
    form = forms.PatientCheckinForm()
    return render(request, 'patientRecords/checkin.html', {'patient': patient, 'form':form})
Run Code Online (Sandbox Code Playgroud)

When I submit the patient form filled out as a POST method, I still need access to the patient_id. Currently this is the view that accepts the filled form:

def CheckinSubmit(request):
if request.method == 'POST':
    form = forms.PatientCheckinForm(request.POST, request.FILES)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.date_time_of_checkin = dt.now()
        instance.patient = patient.patient_id
        instance.save()
        return redirect('patientRecords/index.html')
Run Code Online (Sandbox Code Playgroud)

I want to set the instance.patient to the patient_id that was part of patient from the Checkin view. Is there a way to pass the patient data back along with the POST method or is there another way this can be done?

For reference, here is my template and I am using ModelForm not form.

{% block content %}

<div class="container">
  <h1>Patient Checkin</h1>
  <h2>{{patient.first_name}} {{patient.last_name}}</h2>
</div>
<div class="container">
  <form  action="{% url 'patientRecords:checkinsubmit' %}" method="POST" class="form">
    {% csrf_token %}
    {% bootstrap_form form %}
    {% buttons %}
        <button type="submit" class="btn btn-primary">Submit</button>
    {% endbuttons %}
  </form>
</div>

{% endblock %}
Run Code Online (Sandbox Code Playgroud)

Thanks in advance!

nb1*_*987 9

You should be able to simply add a hidden input to your form to capture the patient ID:

{% block content %}

<div class="container">
  <h1>Patient Checkin</h1>
  <h2>{{patient.first_name}} {{patient.last_name}}</h2>
</div>
<div class="container">
  <form  action="{% url 'patientRecords:checkinsubmit' %}" method="POST" class="form">
    <input type="hidden" name="patient_id" value="{{patient.patient_id}}" />
    {% csrf_token %}
    {% bootstrap_form form %}
    {% buttons %}
        <button type="submit" class="btn btn-primary">Submit</button>
    {% endbuttons %}
  </form>
</div>

{% endblock %}
Run Code Online (Sandbox Code Playgroud)

(Note this assumes that the patient ID is accessible from the patient_id property of the patient object.)

Then, in your CheckinSubmit method, you can access this value via request.POST.get('patient_id')

Alternatively, it appears that your check in form loads with the patient ID in the URL. In your CheckinSubmit method, you should be able to access this URL through the request.META.HTTP_REFERER property. You could then parse the URL (e.g., using request.META.HTTP_REFERER.split('/')[len(request.META.HTTP_REFERER.split('/')) - 1] to pull out the patient ID.