1

can insert loop data into django model?..

here my code. on view.py

    class EmpCreateView(CreateView):
        fields = ()
        model = models.Employee

        def form_valid(self, form):
            self.object = form.save(commit=False)

            loopdo = 5
            while loopdo > 0:
                self.object.name = "work?" 
                self.object.no = loopdo
                self.object.save()
                loopdo -= 1

            return super(ModelFormMixin, self).form_valid(form)

it's only insert 1 data.

4
  • Could it be that your data model doesn't allow some of the data taken from the form to be duplicated (unique = true) ? That way most of the insertions would fail since you can't have, for example, the same name twice. Commented Apr 22, 2018 at 3:14
  • Don't use loop for save multiple objects, use bulk_create.. it is an advice only Commented Apr 22, 2018 at 3:14
  • @BurakÖztürk bulk create can use data from another model?... Commented Apr 22, 2018 at 3:16
  • I get super(type, obj): obj must be an instance or subtype of type Commented Jun 2, 2022 at 5:12

1 Answer 1

1

You should try setting the primary key to None.

See this answer: How can I save the same form more than once in Django 1.8?

I got my reference from: Save multiple data using loops in django models using save function with admin save button

Sign up to request clarification or add additional context in comments.

2 Comments

Awesome! :). When you get a chance, can you accept the answer? It helps other users know the question is answered and also my rating!
Why are we not advising a formset here?

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.