0

I have the following code:

def test_view(request, list):

    my_form = MyForm(request.POST)
    for x in list:
        my_instance = my_form.save(commit = false)
        my_instance.variable_field = x['content']
        my_form.save()

Now for some reason, new record is inserted into the DB only during the first iteration. My guess is that it has something to do with form prefixes, but I still didn't come across any material in the doc describing how to tackle this situation appropriately.

UPDATE: Just to clarify: I have a form which underlying instance contain a field that I've excluded from the form and turned it into a selectize element in my interface. The user can choose multiple options in the selectize, that's why I need the for-loop in the code extract.

1 Answer 1

1

What about doing this:

def test_view(request, list):

   my_form = MyForm(request.POST) 

   for x in list:
        my_instance = my_form.save(commit = false)
        if my_instance.id:
                my_instance.id = None
        my_instance.variable_field = x['content']
        my_form.save()
Sign up to request clarification or add additional context in comments.

2 Comments

Well, two comments. First, you don' need the "if my_instance.id:", second, do you think it's the clearest method to do it ? I will add an update to the question to clarify the issue a bit
The goal behind this code was that for any item in list there will be an instance saved to the database. The my_instance=None just copies the instance (AFAIK this is still the standard way of copying instances in django)..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.