Login

Use pexpect to control manage.py syncdb or anything else

Author:
aafshar
Posted:
March 16, 2007
Language:
Python
Version:
Pre .96
Score:
6 (after 6 ratings)

You can read the short blog article that gives a description of what I was thinking when I attempted this. Note: UNIX only. Sorry!

 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 = '[email protected]'

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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 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()

#

Please login first before commenting.