0
votes

Django 1.10.

Studying formsets. Interested in method has_changed.

Trying to learn by analogy with forms: "When the form is submitted, we reconstruct it and provide the original data so that the comparison can be done" (https://docs.djangoproject.com/es/1.10/ref/forms/api/#checking-which-form-data-has-changed).

So, at the server we need to save initial data. Then Django renders html: a form is solitary, our formset being just input tags with special ids. User submits the form. We catch request.POST.

Here we have to recunstruct the formset.

The problem is that being submitted, the formset looks like this:

QueryDict: <QueryDict: {'csrfmiddlewaretoken': ['X5RMIXfwfQH9zUYz7ODw59UPEr1AQaeciJR2qrLU64ipbBnbu4jKEcW0nVc019vC', 'X5RMIXfwfQH9zUYz7ODw59UPEr1AQaeciJR2qrLU64ipbBnbu4jKEcW0nVc019vC'], 'form-0-pub_date': ['2016-01-01'], 'form-1-pub_date': [''], 'form-0-title': ['Initial title'], 'form-1-title': ['']}>

To the best of my ability, I only can think of:

1. Getting keys:

request.POST.keys()

Result:

dict_keys: dict_keys(['csrfmiddlewaretoken', 'form-0-pub_date', 'form-1-pub_date', 'form-0-title', 'form-1-title'])

2. splitting the keys like str.split('-'). Then I'll have somehow handle the data.

def post(self, request):
    l = list(request.POST.keys())
    l.remove("csrfmiddlewaretoken")
    for element in l:
        sp = element.split("-")
    pass

Well, this is all cumbersome. And I feel clumsy. So clumsy that I don't even know whether there is a practical value in the has_changed method.

Could you suggest me an elegant way to reconstruct a formset.

1

1 Answers

0
votes

I have found the answer. It is written further in the documentation: https://docs.djangoproject.com/en/1.10/topics/forms/formsets/#using-a-formset-in-views-and-templates

ArticleFormSet = formset_factory(ArticleForm)
if request.method == 'POST':
    formset = ArticleFormSet(request.POST, request.FILES)