Django Admin后台使用

视频资料

http://www.pythoner.cn/course/topic/django-web-development/




Django Admin

1,创建1个项目

django-admin.py startproject csvt05

2,创建一个app

django-admin.py startapp blog

修改配置文件

vim csvt05/settings.py

#配置数据库设置,这里使用sqlite3
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'csvt05.db',                      # Or path to database file if using sqlite3.
        # The following settings are not used with sqlite3:
        'USER': '',
        'PASSWORD': '',
        'HOST': '',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
        'PORT': '',                      # Set to empty string for default.
    }
}
#APPS模块加入blog,开启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',
)

#增加模块

vim blog/models.py

from django.db import models
sex_choices = (
        ('f', 'Famale'),
        ('m', 'Male'),
        )
class User(models.Model):
    name = models.CharField(max_length=30)
    sex = models.CharField(max_length=1, choices=sex_choices)


#同步数据库

python manage.py syncdb


在这里创建后台管理的账号和密码,等会后台登陆要使用。


#编辑 csvt05下的urls.py 去掉 下面三行前面的注释

vim csvt05/urls.py

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'^$', 'csvt05.views.home', name='home'),
    # url(r'^csvt05/', include('csvt05.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)),
)

#启动开发服务器

python manange.py runserver


现在就可以登录后台管理界面。如下图

http://127.0.0.1:8000/admin

输入同步数据库的时候创建的用户和密码

这里会不显示blog的数据库表,我们要在blog/下面创建个 admin.py的文件来注册一下blog的数据库

编辑创建 blog/admin.py文件,

from django.contrib import admin
from blog.models import User
admin.site.register(User)

#重启开发服务器,然后重新登陆后台即可

最后我们可以在这里进行数据库表的数据的怎家和删除,例如blog的user表的数据

选择一个性别之后点击保存。会增加一个对象,如下图但是但是显示的是一个 User object,

然后我们修改 blog/models.py 增加一些内容让后台显示更加清晰,增加后models.py如下

from django.db import models
sex_choices = (
        ('f', 'Famale'),
        ('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

重新刷新页面显示结果为


###


你可能感兴趣的:(database,配置文件,Settings,default,following)