Saturday 3 January 2015

use admin page to config database in Django

  1. Create a project named csvt05 and an application called blog

  1. Add an application in settings.py
INSTALLED_APPS = (
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   'blog',
)

  1. Make sure admin url is added

root@10:/home/python/django/csvt05# nano csvt05/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns('',
   # Examples:
   # url(r'^$', 'csvt05.views.home', name='home'),
   # url(r'^blog/', include('blog.urls')),

   url(r'^admin/', include(admin.site.urls)),
)
  1. Add tables

root@10:/home/python/django/csvt05# nano blog/models.py
from django.db import models

sex_choices = (
   ('f','female'),
   ('m','male'),
)

class User(models.Model):
   name = models.CharField(max_length=30)
   sex = models.CharField(max_length=1, choices=sex_choices)

   def __unicode__(self):
       return self.name

  1. Register to admin.py

root@10:/home/python/django/csvt05# nano blog/admin.py

from django.contrib import admin
from blog.models import User

admin.site.register(User)

  1. Sync db
root@10:/home/python/django/csvt05# python manage.py syncdb
Operations to perform:
 Apply all migrations: admin, contenttypes, auth, sessions
Running migrations:
 Applying contenttypes.0001_initial... OK
 Applying auth.0001_initial... OK
 Applying admin.0001_initial... OK
 Applying sessions.0001_initial... OK

You have installed Django's auth system, and don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (leave blank to use 'colin'): colin
Email address: colin@1.com
Password:
Password (again):
Superuser created successfully.

root@10:/home/python/django/csvt05# python manage.py migrate
root@10:/home/python/django/csvt05# python manage.py makemigrations

  1. Test

root@10:/home/python/django/csvt05# sqlite3 db.sqlite3
SQLite version 3.7.9 2011-11-01 00:52:41
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .tables
auth_group                  blog_user
auth_group_permissions      django_admin_log
auth_permission             django_content_type
auth_user                   django_migrations
auth_user_groups            django_session
auth_user_user_permissions
sqlite> select * from blog_user
  ...> ;
1|alen|m
2|max|f
3|tom|m

No comments:

Post a Comment