zinon zinon - 1 year ago 27
Python Question

Retrieved data displayed in forms cannot be submitted correctly in django

I retrieve data from a database and show them to their corresponding forms in template. Then, when I'm trying to update a field, these forms do not submit the retrieved data and as a result forms are not validated.

Do you have any idea how to fix this problem?

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 = []


Does the way I retrieve data matter?

I use the above code in another template to find a patient.

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

Answer Source

I found the solution, working on @brunodesthuilliers solution!

The problem is that I have to pass the instance=patient even after the request.POST, in order the django understands to deal data as an update.

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download