DJANGO - Issue using formsets

2019-05-18 06:18发布

So I have a form class in my forms.py file that i will use for creating a formset with a variable number of forms (the client will set the number of forms to display).

The form class would be like this:

forms.py

from django import forms

class example(forms.Form):

    CHOICES = [('choice1', 'choice1'), ('choice2', 'choice2')]

    field1 = forms.IntegerField()
    field2 = forms.DateTimeField()
    field3 = forms.ChoiceField(choices = CHOICES)

And then in my views.py file i have something like this:

views.py

from myproject.forms import example
from myproject.models import example_model


from django.forms.formsets import formset_factory
from django.http.response import HttpResponseRedirect
from django.shortcuts import render_to_response

def add_example_form(request, model_id, num_forms): # the num_forms is passed previously from another view via URL

    mymodel = example_model.objects.get(pk = model_id) #I'll use the formset for filling sa field of a model which couldn't be filled in the creation of the model for whatever reason
    data1 = None
    data2 = None
    data3 = None

    data_total = []

    exampleFormset = formset_factory(example, extra = int(num_forms))

    if request.method == 'POST':

        formset = exampleFormset(request.POST)
        if formset.is_valid():

            for form in formset:
                data1 = form.cleaned_data['field1']
                data2 = form.cleaned_data['field2']
                data3 = form.cleaned_data['field3']

                data_total.append([data1, data2, data3])

            #Then I save these fields into a field of a model that I have saved on my main database
            mymodel.somefield = data_total
            mymodel.save()

            return HttpResponseRedirect('/someURL/')

        else:
            raise Exception('The introduced fields are wrong!')

    else:
        formset = exampleFormset()

    return render_to_response('someURL/example.html',{'formset': formset}, context_instance = RequestContext(request))

In my html template file I call the formset using the following format:

example.html

<html>
    <body>
        <h2>Fill the forms:</h2>
        <form method='post' action=''> {% csrf_token %}
            {{ formset.management_form }}
            {% for form in formset %}

                {{ form }} <br>

            {% endfor %}
            <p><input type='submit' value='Submit'/></p>
        </form>
    </body>
</html>

So when i run the server and i connect with the client to this view all seems to work correctly, it loads the proper number of forms with the is_valid() to True and the HTTP POST request seems free of errors. The problem is that the information that I get from the submited formset is wrong: it only takes the info of the fields of the LAST form and copies it to the rest of the forms but it only occurs with the DateTimeField and the ChoiceField, the IntegerField fields are correct. For example, this would be my view from the client:

Fill the forms: (number of forms = 2)

field1: 1

field2: 2001-01-01 01:01:01

field3: (we select the 'choice1' choice)

field1: 2

field2: 2002-02-02 02:02:02

field3: (we select the 'choice2' choice)

Submit

When the submit button is clicked, all the process seems ok but the data retrieved by the formset in field2 and field3 of both forms is the one from the second form so in reality i have saved in my database the following content:

field1: 1

field2: 2002-02-02 02:02:02

field3: 'choice2'

field1: 2

field2: 2002-02-02 02:02:02

field3: 'choice2'

I can't figure where is the problem here since the code is pretty simple or if this is a known django bug (which I don't think so), any help would be so much appreciated. Thanks in advance.

0条回答
登录 后发表回答