无法在django中正确提交表单中显示的检索数据

时间:2014-11-17 11:11:56

标签: python django django-templates django-views

我从数据库中检索数据并将其显示在模板中的相应表单中。然后,当我尝试更新字段时,这些表单不会提交检索到的数据,因此不会验证表单。

你知道如何解决这个问题吗?

views.py

def results(request):

    context = RequestContext(request)
    myid = request.GET.get('id', '')
    diag_option = 0
    print "my id", myid
    if request.method == 'POST':
        my_demographics = DemographicForm(request.POST or None, prefix="demo")

        if my_demographics.is_valid():
            my_demographics_object = my_demographics.save()

    else:

        patient = Demographic.objects.get(patient_id = myid)

        my_demographics = DemographicForm(instance=form_data)      

    return render_to_response('input.html', {'frm':my_demographics}, context)

template results.html

<form class="form-horizontal" method="post" id="input">
    {% csrf_token %}

    <div class="tab-pane" id="mytab">
        <div class="tab-content">
            <div class="tab-pane fade in active" id="1">
                <!--<input type="hidden" name="form_id" value="demographics">-->
                <div class="container"> {%crispy frm%}</div>

            </div>
        </div>
    </div>
</form>

forms.py

class DemographicForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(DemographicForm, self).__init__(*args, **kwargs)
        self.helper=FormHelper(self)
        self.fields['date_of_birth'].widget = widgets.AdminDateWidget()
        self.helper.layout = Layout(
            'national_health_care_pat_id',
            'patient_hospital_file_number',
            'patient_id',
            'given_name',
            'surname',
            'date_of_birth',

            FormActions(
                Submit('submit', "Save changes"),
                Submit('cancel', "Cancel")
            ),

        )
        self.helper.form_tag = False
        self.helper.form_show_labels = True

    class Meta:
        model = Demographic
        exclude = []

检索数据的方式是否重要?

我在另一个模板中使用上面的代码来找到病人。

patient = Demographic.objects.select_for_update().filter(patient_id = myid)

1 个答案:

答案 0 :(得分:0)

我找到了解决方案,致力于@brunodesthuilliers解决方案!

问题是我必须在instance=patient之后传递request.POST,以便django理解将数据作为更新处理。

<强> views.py

def results(request):

    context = RequestContext(request)
    myid = request.GET.get('id', '')

    if request.method == 'POST':
        with transaction.atomic():
            patient = Demographic.objects.get(patient_id=myid)

        my_demographics = DemographicForm(request.POST or None, instance=patient)

        if my_demographics.is_valid():
            my_demographics_object = my_demographics.save()

    else:
        with transaction.atomic():
            print "HERE ELSE"
            patient = Demographic.objects.get(patient_id=myid)

        my_demographics = DemographicForm(instance=patient)

    return render_to_response('input.html', {'frm':my_demographics}, context)