Saving the responses

We want to save the response of the user filling in one of our dynamic forms. As the data from a dynamic form will also be dynamic, we need to store an unknown number of fields and their values in our database. As we have already seen, JSON is a reasonable way to store such data. Let's create a new model in main/models.py to store the responses:

class FormResponse(models.Model):
    form = models.ForeignKey(FormSchema)
    response = JSONField()

Next, create and run the migrations to add this new model to our database:

> python manage.py makemigrations main
Migrations for 'main':
  0002_formresponse.py:
    - Create model FormResponse
> python manage.py migrate main
Operations to perform:
  Apply all migrations: main
Running migrations:
  Rendering model states... DONE
  Applying main.0002_formresponse... OK

Now that we have our model, we need to save valid responses for our forms in this model. The form_valid method of CustomFormView is the correct place to add this logic. First, we need to import a few things from Django and our new model at the top of our main/views.py file:

from django.core.urlresolvers import reverse
from django.http.response import HttpResponseRedirect

from main.models import FormResponse

Then, add a form_valid method with this code to the CustomFormView class:

def form_valid(self, form):
    custom_form = FormSchema.objects.get(pk=self.kwargs["form_pk"])
    user_response = form.cleaned_data

    form_response = FormResponse(form=custom_form, response=user_response)
    form_response.save()

    return HttpResponseRedirect(reverse('home'))

That's it. Now try submitting the custom form that we created earlier and if the data was valid, you should be redirected to the home page after your response was saved. Right now, we have no way to see these responses in the frontend; however, we can use the Django shell to make sure that our data has been saved. Start the shell with the following command:

> python manage.py shell

Then use the following lines of code to see the response that was saved:

> from main.models import FormResponse
> FormResponse.objects.all()[0].response
{u'age': 27,
 u'city': u'Dubai',
 u'country': u'UAE',
 u'name': u'Jibran',
 u'time_lived_in_current_city': u'3 years'}

You should see the data that you entered when saving the form. Now let's create a screen where our customers can see the responses for their custom forms.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.232.239