django: db

本讲演示简单使用 Django Admin 功能。

一,修改 settings.py,添加 admin 应用:

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)

二,修改 urls.py,添加 /admin 映射:

from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

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

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
    url(r'^index/$','blog.views.index'),
)

三,修改 blog/models.py 加入 User 数据表后同步数据库:

from django.db import models

class Employee(models.Model):
        name = models.CharField(max_length=20)  # map 'name' field to db

        def __unicode__(self):
                return self.name

class Entry(models.Model):
        name = models.CharField(max_length=20)

        def __unicode__(self):
                return self.name

class Blog(models.Model):
        name = models.CharField(max_length=20)
        entry = models.ForeignKey(Entry)                # Many-To-One Map: Blogs - Entry

        def __unicode__(self):
                return self.name

sex_choices = {
        ('F', 'Female'),
        ('M', 'Male')
}

class User(models.Model):
        name = models.CharField(max_length=20)
        sex = models.CharField(max_length=1, choices=sex_choices)
[root@bogon csvt03]#  python manage.py syncdb
Creating tables ...
Creating table blog_user
Creating table django_admin_log
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)

四,在 blog/ 下创建 admin.py,注册 User 表,以供 Django-Admin 对 User 表的管理:

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

admin.site.register(User)

五,打开开发服务器 python manage.py runserver 之后,在 http://127.0.0.1:8000/admin 中可以对用户及数据库进行方便管理。

原文地址:https://www.cnblogs.com/exclm/p/3364349.html