Use pexpect to control manage.py syncdb or anything else

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
PASSWORD = '123'    # replace this with something good
EMAIL = 'aafshar@gmail.com'

import pexpect

# spawn the child process
child = pexpect.spawn('python manage.py syncdb')

# Wait for the application to give us this text (a regular expression)
child.expect('Would you like to create one now.*')

# Send this line in response
child.sendline('yes')

# Again wait for this, and send what is needed
child.expect('Username.*')

# A blank string for the default username
child.sendline('')

# And so it goes on
child.expect('E-mail.*')
child.sendline(EMAIL)
child.expect('Password.*')
child.sendline(PASSWORD)
child.expect('Password.*')
child.sendline(PASSWORD)

# This means wait for the end of the child's output
child.expect(pexpect.EOF, timeout=None)

More like this

  1. Control FCGI processes through management by nipuL 6 years ago
  2. web-key: Base64 Shared Secret for Access Control by sbw 4 years, 11 months ago
  3. Export models as json by aconbere 7 years, 1 month ago
  4. Table Creation Using ORM Standalone by EliAndrewC 6 years, 2 months ago
  5. invoke pyflakes via manage.py by mpasternacki 4 years, 6 months ago

Comments

whiteinge (on March 16, 2007):

Good solution for restoring the admin stuff when django-admin.py reset app isn't enough and you have to recreate the whole db.

Another method, which works for non-admin stuff too, is to create a little script that you run like python devel_populate.py (example below). The only caveat is that you need to set up your PYTHONPATH and DJANGO_SETTINGS_MODULE first (ie. using django-admin.py not manage.py).

from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.flatpages.models import FlatPage
from yourapp.yourproj.models import UserProfile

u = User.objects.create(
    username='',
    first_name='',
    last_name='',
    email='',
    is_superuser=True,
    is_staff=True,
    is_active=True
)
u.set_password('changeme')
u.save()

s = Site.objects.get(id=1)
s.domain='example.com'
s.name='Example.com'
s.save()

UserProfile.objects.create(stuffgoeshere)

f = FlatPage.objects.create(
    url='/about/',
    title='About Us',
    content='All about our company.'
)
f.sites.add(Site.objects.get(id=1))
f.save()

#

(Forgotten your password?)