Django 基础知识

时间:2022-04-09 03:45:30

Django Models

django 本身提供了非常强大易使用的ORM组件,并且支持多种数据库,如sqllite,mysql,progressSql,Oracle等,当然最常用的搭配还是mysql,要启用orm,

先要配置好连接数据 的信息

我们使用MySQL配置

1)首选在setting里面配置驱动

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'OldboyWebsite', #确保此数据库已存在
        'HOST':'',                           #mysql主机名
        'PORT':'',                           #端口
        'USER':'root',                     #用户名
        'PASSWORD':''                  #密码
    }
}

Django ORM语法,为了更好的理解,我们来做一个基本的 书籍/作者/出版商 数据库结构。 我们这样做是因为 这是一个众所周知的例子,很多SQL有关的书籍也常用这个举例。

我们来假定下面的这些概念、字段和关系:

  • 一个作者有姓,有名及email地址。

  • 出版商有名称,地址,所在城市、省,国家,网站。

  • 书籍有书名和出版日期。 它有一个或多个作者(和作者是多对多的关联关系[many-to-many]), 只有一个出版商(和出版商是一对多的关联关系[one-to-many],也被称作外键[foreign key])

from django.db import models

class Publisher(models.Model):
    name = models.CharField(max_length=)
    address = models.CharField(max_length=)
    city = models.CharField(max_length=)
    state_province = models.CharField(max_length=)
    country = models.CharField(max_length=)
    website = models.URLField()

class Author(models.Model):
    first_name = models.CharField(max_length=)
    last_name = models.CharField(max_length=)
    email = models.EmailField()

class Book(models.Model):
    name = models.CharField(max_length=)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField()

更多models field 字段:https://docs.djangoproject.com/en/1.9/ref/models/fields/


模型安装

完成这些代码之后,现在让我们来在数据库中创建这些表。 要完成该项工作,第一步是在 Django 项目中 激活这些模型。 将上面的模型所在的app (此例子app是books) 添加到配置文件的已安装应用列表中即可完成此步骤。

再次编辑 settings.py 文件, 找到 INSTALLED_APPS 设置。 INSTALLED_APPS 告诉 Django 项目哪些 app 处于激活状态。 缺省情况下如下所示:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01',
]

app01是项目名称

使数据库按照模型的配置生成表结构

C:\Users\Administrator\PycharmProjects\Study>python manage.py makemigrations
C:\Users\Administrator\PycharmProjects\Study>python manage.py migrate

然后进行测试


Django Form表单

django中的Form有两种功能

输入html

验证用户输入

ModelFrom

在使用Model和Form时,都需要对字段进行定义并指定类型,通过ModelForm则可以省去From中字段的定义

class BookModelForm(forms.ModelForm):
    class Meta:
        model = models.Book
        #fields = ('name','publish_date')  #显示那些字段
        exclude = ()                     #排除那些字段
        widgets = {
            'name' : forms.TextInput(attrs={'class':"form-control"}),
        }

form

def book_modelform(request):
    form = forms.BookModelForm()  #如果是get 就直接返回return 页面
    if request.method == 'POST':    #如果是post
        print (request.POST)
        form = forms.BookModelForm(request.POST)
        if form.is_valid():         #验证
            print ("form is ok")
            print (form.cleaned_data)
            form.save()
    return render(request, 'app01/book_modelform.html', {'book_form': form})

视图 views

from app01 import views
from django.conf.urls import url,include
urlpatterns = [
    url(r'book_modelform/$',views.book_modelform),

]

Url

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form method="post" action="">{% csrf_token %}
        {% for ele in book_form %}
           <div class="form-row"> {{ ele.name}} {{ ele }} {{ ele.errors }} </div>
        {% endfor %}
        <input type="submit" value="创建新书">
    </form>
</body>
</html>

模板文件

Django Admin

django amdin是django提供的一个后台管理页面,改管理页面提供完善的html和css,使得你在通过Model创建完数据库表之后,就可以对数据进行增删改查,而使用django admin 则需要以下步骤:

  • 创建后台管理员
  • 配置url
  • 注册和配置django admin后台管理页面

1 创建后台管理员

python manage.py createsuperuser

2 配置后台管理url

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

3 注册和配置django admin 后台管理页面

a 在admin中执行如下配置

from django.contrib import admin
from app01 import models

admin.site.register(models.Author)
admin.site.register(models.Book,BookAdmin)
admin.site.register(models.Publisher)

b 自定义页面展示

class BookAdmin(admin.ModelAdmin):
    list_display = ('name','publisher','publish_date')

admin.site.register(models.Author)
admin.site.register(models.Book,BookAdmin)
admin.site.register(models.Publisher)

注:如果是多对多 是不能显示的

c 添加页面搜索功能

class BookAdmin(admin.ModelAdmin):
    list_display = ('name','publisher','publish_date')
    search_fields = ('name','publisher__name')

admin.site.register(models.Author)
admin.site.register(models.Book,BookAdmin)
admin.site.register(models.Publisher)

d 添加过滤功能

class BookAdmin(admin.ModelAdmin):
    list_display = ('name','publisher','publish_date')
    search_fields = ('name','publisher__name')
    list_filter = ('publisher','publish_date')

admin.site.register(models.Author)
admin.site.register(models.Book,BookAdmin)
admin.site.register(models.Publisher)

e 其它功能

class BookAdmin(admin.ModelAdmin):
    list_display = ('id','name','publisher','publish_date')
    search_fields = ('name','publisher__name')
    list_filter = ('publisher','publish_date')
    list_editable = ('name','publisher','publish_date')  #编辑功能
    list_per_page = 5                  #分页
    filter_horizontal = ('authors',)   #选项功能
    raw_id_fields = ('publisher',)

admin.site.register(models.Author)
admin.site.register(models.Book,BookAdmin)
admin.site.register(models.Publisher)

f admin action用法

class Book(models.Model):
    name = models.CharField(max_length=)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    publish_date = models.DateField()
    status_choices = (('published',u'已出版'),
                     ('producing',u'待出版'),
                     ('forbidden',u'禁书'),
                      )
    status = models.CharField(choices=status_choices,max_length=,default='producing')
    def __unicode__(self):
        return "%s" %self.name
    class Meta:
        verbose_name_plural = u'书籍'

models

admin.py

def make_forbidden(modelAdmin,request,Queryset):
    print ('-->',request,Queryset)
    Queryset.update(status='forbidden')
    make_forbidden.short_description = "Set to forbidden"

class BookAdmin(admin.ModelAdmin):
list_display = ('id','name','publisher','publish_date','status')
search_fields = ('name','publisher__name')
list_filter = ('publisher','publish_date')
list_editable = ('name','publisher')
list_per_page = 5
filter_horizontal = ('authors',)
# raw_id_fields = ('publisher',)
actions = [make_forbidden,]

admin.site.register(models.Author)
admin.site.register(models.Book,BookAdmin)
admin.site.register(models.Publisher)
 

g 状态显示颜色

class Book(models.Model):
    name = models.CharField(max_length=)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    publish_date = models.DateField()
    status_choices = (('published',u'已出版'),
                     ('producing',u'待出版'),
                     ('forbidden',u'禁书'),
                      )
    status = models.CharField(choices=status_choices,max_length=,default='producing')
    def __unicode__(self):
        return "%s" %self.name
    class Meta:
        verbose_name_plural = u'书籍'

    def colored_status(self):
        if self.status == "published":
            format_td = format_html('<span style="padding:2px;background-color:yellowgreen;color:white">已出版</span>')
        elif self.status == "producing":
            format_td = format_html('<span style="padding:2px;background-color:gray;color:white">待出版</span>')
        elif self.status == "forbidden":
            format_td = format_html('<span style="padding:2px;background-color:orange;color:white">禁书</span>')

        return format_td
    colored_status.short_description = 'status'

admin.py

from django.contrib import admin

# Register your models here.
from app01 import models

def make_forbidden(modelAdmin,request,Queryset):
    print ('-->',request,Queryset)
    Queryset.update(status='forbidden')
    make_forbidden.short_description = "Set to forbidden"

class BookAdmin(admin.ModelAdmin):
    list_display = ('id','name','publisher','publish_date','colored_status')
    search_fields = ('name','publisher__name')
    list_filter = ('publisher','publish_date')
    list_editable = ('name','publisher')
    list_per_page =
    filter_horizontal = ('authors',)
    # raw_id_fields = ('publisher',)
    actions = [make_forbidden,]

admin.site.register(models.Author)
admin.site.register(models.Book,BookAdmin)
admin.site.register(models.Publisher)