1、models 要创建好,规划好自己的表,以及各种表关系
2、url正则要写好
3、settings的配置
4、利用bootstarp 进行布局更漂亮哦
5、注意orm 各种类型的转换还有取值。
6、模板语法
下面上菜
G:.
├─.idea
│ ├─dataSources
│ └─inspectionProfiles
├─app01
│ ├─migrations
│ │ └─__pycache__
│ ├─static
│ │ └─css
│ └─__pycache__
├─books
│ └─__pycache__
└─templates
settings.py
"""
Django settings for books project.
Generated by 'django-admin startproject' using Django 2.0.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'm-zu@pls$#8)6njw1ar5#t#tx#fcfhe7(iaygkg(y4l^x@!!ix'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01.apps.App01Config',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'books.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'books.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'books',
'HOST': '172.16.0.30',
'PORT': '3306',
'USER': 'root',
'PASSWORD': 'zabbix',
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django.db.backends': {
'handlers': ['console'],
'propagate': True,
'level': 'DEBUG',
},
}
}
urls.py
"""books URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from app01 import views
from django.conf.urls import url
urlpatterns = [
path('admin/', admin.site.urls),
path('index', views.index),
url(r'^editbooks/(?P
url(r'^books/(?P
url(r'^books/$', views.books),
url(r'^addbooks/', views.addbooks, name='addbooks'),
]
views.py
from django.shortcuts import HttpResponse, render, redirect, HttpResponseRedirect
from .models import *
import decimal
from django.db.models import Avg, Sum, Count, Max, Min, F, Q
def index(request):
return HttpResponse('ok')
def books(request):
book_list = Book.objects.all()
author_list = Author.objects.all()
publish_list = Publish.objects.all()
return render(request, 'books.html', {'book\_list': book\_list, 'author': author\_list, 'publish\_list': publish\_list})
def delete(request, nid):
book_obj = Book.objects
print('_________________________________________________________')
print(nid)
book_obj.filter(nid=nid).delete()
print('删除成功')
return redirect('/books')
def addbooks(request):
author_list = Author.objects.all()
publish_list = Publish.objects.all()
if request.method == 'GET':
return render(request, 'addbooks.html', {'publish_list': publish_list, 'author_list': author_list})
else:
try:
title = request.POST.get('title')
price = int(request.POST.get('price'))
pub_date = request.POST.get('pub_date')
publish_id = request.POST.get('publish_id')
autho_id_list = request.POST.getlist('author_id_list') # 当获取多个数值的时候,使用getlist
book_obj = Book.objects.create(title=title, price=price, publishDate=pub_date, publish_id=publish_id)
book_obj.authors.add(*autho_id_list)
except Exception as e:
print(e, '数值郭达')
return redirect('/addbooks')
return redirect('/books')
def editbooks(request, nid):
author_list = Author.objects.all()
publish_list = Publish.objects.all()
book_nid_obj = Book.objects.get(nid=nid)
if request.method == 'GET':
return render(request, 'editbooks.html',
{'author_list': author_list, 'book_nid_obj': book_nid_obj,
'publish_list': publish_list})
else:
# 编辑操作
title = request.POST.get('title')
price = int(request.POST.get('price'))
pub\_date = request.POST.get('pub\_date')
publish\_id = request.POST.get('publish\_id')
author\_id\_list = request.POST.getlist('author\_id\_list') # 当获取多个数值的时候,使用getlist
print(request.POST)
book\_obj\_ed = Book.objects.filter(nid=nid)
print(book\_nid\_obj) # Book 对象
print('--------------------------------------------')
print(book\_obj\_ed) # QueySet
book\_obj\_ed.update(title=title, price=price, publishDate=pub\_date, publish\_id=publish\_id)
book\_nid\_obj.authors.clear()
book\_nid\_obj.authors.add(\*author\_id\_list)
return redirect('/books')
models.py
from django.db import models
class Author(models.Model):
nid = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
age = models.IntegerField()
# 与AuthorDetail建立一对一的关系
authorDetail = models.OneToOneField(to="AuthorDetail", on\_delete=models.CASCADE)
class AuthorDetail(models.Model):
nid = models.AutoField(primary_key=True)
birthday = models.DateField()
telephone = models.BigIntegerField()
addr = models.CharField(max_length=64)
class Publish(models.Model):
nid = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
city = models.CharField(max_length=32)
email = models.EmailField()
class Book(models.Model):
nid = models.AutoField(primary_key=True)
title = models.CharField(max_length=32)
publishDate = models.DateField()
price = models.DecimalField(max_digits=5, decimal_places=2)
# 与Publish建立一对多的关系,外键字段建立在多的一方
publish = models.ForeignKey(to="Publish", to\_field="nid", on\_delete=models.CASCADE)
# 与Author表建立多对多的关系,ManyToManyField可以建在两个模型中的任意一个,自动创建第三张表
authors = models.ManyToManyField(to='Author', )
templates
books.html
编号 | 名称 | 价格 | 出版社 | 出版日期 | 作者 | 操作 |
---|---|---|---|---|---|---|
{{ book.nid }} | {{ book.title }} | {{ book.price }} | {{ book.publish.name }} | {{ book.publishDate | date:'Y-m-d'}} | {% for auth in book.authors.all.values %} {% if forloop.last %} {{ auth.name }} {% else %} {{ auth.name }} , {% endif %} {% endfor %} | 编辑 删除 |
addbooks.html
editbooks.html
其他功能等我学会了再来
手机扫一扫
移动阅读更方便
你可能感兴趣的文章