1

How to create ten User objects?

for i in range(11):
    i = User.objects.create(username = 'test125', email='[email protected]', password='pass1')

Column username is not unique

1
  • username='test{}'.format(i) Commented Jan 24, 2013 at 15:24

3 Answers 3

3

You have a unique contraint on the username field which means you cannot have two objects with the same username. Try this:

for i in range(10):
    i = User.objects.create(username = 'testX%s' % i, email='[email protected]', password='pass1')
Sign up to request clarification or add additional context in comments.

1 Comment

Depending on how many times you're going to loop bulk create would limit hitting the database too much.
1

The problem you are having is that you fixed the username value, so you are trying to create 10 users with the same name.

Just use some kind of variation for the username, like username='testuser-{}'.format(i)

Comments

0

You need to change the name for each record.

You are naming each user "test125". Try concatenating the index for each new record:

for i in range(11):
    i = User.objects.create(username = 'test%s' % i, email='[email protected]', password='pass1')

Most likely you will need to do the same with your 'email' column:

for i in range(11):
    i = User.objects.create(username = 'test%s' % i, email='test%[email protected]' % i, password='pass1')

Also, usually is not a good idea to assign your new object to the same variable as your index. Try something different than 'i'.

Comments

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.