Anonymous questionnaire: Best approach

Hi,

I am currently working an an anonymous questionnaire which contains several questions in different views.

As it is anonymous I think the best approach is to use the native session framework of Django.

So I plan to store the user responses as cookies on the server side.

Example, the following two lines will store a cookie on the server side containing the question 1 response and prompt the user browser to set a session ID cookie, so that the next question will be correctly linked with the session (using the session ID provided by the client’s browser):

request.session['question 1'] = 'response from the user'
HttpResponse('Thank you for your submit')

Then on my admin view, I will iter over the Session objects (from django.contrib.sessions.models.Session) and get the responses.

The problem I see, is that the cookies are not structured data, it’s only string, if the user response should be a date or any more complex data structure I cannot modeling it.

Is there a simple possibility to define my data models and link it with the current anonymous session ?

Thank for your help.

François

Hi Francois :wave:

By default Django serializes the session as JSONs (https://docs.djangoproject.com/en/3.1/topics/http/sessions/#session-serialization), so you could keep storing the answer like you’ve showed, or even using a list:

request.session['answers'] = ['answer1', 'answer2']

There are some gotchas regarding when the session is saved, that you must be aware of: https://docs.djangoproject.com/en/3.1/topics/http/sessions/#when-sessions-are-saved

If you want a way to “link” the data from your session to a model that you have, I think a feasible way to do so is storing the primary key from the model you are trying to connect:

request.session['answers'] = [{'question_id': 1, 'answer': 'answer1'}, ...]

About complex data, if I’m not wrong the default serializer relies on json library (https://github.com/django/django/blob/master/django/contrib/sessions/serializers.py#L20 and https://docs.python.org/3/library/json.html). So it will support lists, tuples, dicts, booleans, etc. But you got a point regarding dates… you might need to do it by yourself: https://stackoverflow.com/questions/45983551/django-sessions-handling-of-datetime-types

request.session['answers'] = [{'question_1': 1, 'answer': 'answer1', 'created_at': str(datetime.now())}]

But I would recommend storing simple data using sessions and connect them to a model instance being stored in a regular database. That’s the idea behind user session in Django.

If you want something ready to use, django-formtools might be the library you are looking for:

I hope it helps :raised_hands: