科技文章阅读:前端
""" Django settings for DjangoURL project. Generated by 'django-admin startproject' using Django 2.1.3. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '77g^#&!t_o%%5u8(3^6%(%y&37kazp4@77ij@th^o#qz0k6ye)' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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 = 'DjangoURL.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 = 'DjangoURL.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators 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', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/'
from django.shortcuts import render from django.http import HttpResponse # Create your views here. def book(request): return HttpResponse("图书首页") def book_detail(request, book_id, category_id): text = "您获取的图书的id是:%s,图书分类为:%s" % (book_id, category_id) return HttpResponse(text) def auth_detail(request): author_id = request.GET.get('id') text = '做者的id是:%s' % author_id return HttpResponse(text)
在app中定义urls.py文件并在urls.py中进行include引入;python
若是项目变得愈来愈大,那么url会变得愈来愈多,若是都放在主要的’urls.py‘文件中,那么后续将不太好管理,所以咱们能够将每个app本身url放到本身的app/urls.py文件中进行管理;mysql
通常咱们都会在每一个app下新创建一个叫作urls.py的文件,用来存储本身的”子url“;web
app/urls.py文件内容以下:正则表达式
from django.urls import path from book import views urlpatterns = [ path('', views.book), path('detail/<book_id>/<category_id>/', views.book_detail), path('author/', views.auth_detail), path('publisher/<int:publisher_id>/', views.publisher_detail), path('book_list/', views.book_list), ]
主要的urls.py文件内容以下:sql
from django.contrib import admin from django.urls import path from django.urls import include from django.http import HttpResponse from django.urls import converters from book import views def index(request): return HttpResponse("豆瓣网首页") urlpatterns = [ path('admin/', admin.site.urls), path('', index), path('book/', include('book.urls')) ]
由于url是常常发生变化的,若是在代码中写死,可能会常常全局改动代码,给url取个名字,之后使用url时候,就使用他的名字进行reverse反转便可,就不须要写死url了,好处多多哦!数据库
在多个app之间,有可能产生同名的url,这种几率在开发过程当中仍是极高的,这个时候为了不反转url的时候产生混淆,可使用”应用命名空间“来作区分,定义应用命名空间很是简单,只要在app的urls.py中添加一个变量名:app_name便可,用来指定这个app的命名空间,示例代码以下所示:django
PS:之后在作反转的时候,可使用以下格式:”应用命名空间:url名称“的方式进行反转;、flask
#!/usr/bin/env python # -*- coding:utf-8 -*- # Project: DjangoURL # Software: PyCharm2018.3 # DateTime: 2018-11-12 21:29 # File: urls.py # __author__: 天晴天朗 # Email: tqtl@tqtl.org from django.urls import path from front import views # 定义应用命名空间 app_name = 'front' urlpatterns = [ path('', views.index, name='index'), path('login/', views.login, name='login'), ]
from django.contrib import admin from django.urls import path from django.urls import include from django.http import HttpResponse urlpatterns = [ path('admin/', admin.site.urls), path('book/', include('book.urls')), path('front/', include('front.urls')), path('cms/', include('cms.urls')), path('cms1/', include('cms.urls',namespace='cms1')), path('cms2/', include('cms.urls',namespace='cms2')), ]
之后在作反转的时候,就能够根据实例命令空间来指定具体的url,实例代码以下:windows
from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): username = request.GET.get('username') if username: return HttpResponse("CMS的首页") else: current_namespace = request.resolver_match.namespace return HttpResponse(reversed("%s:login" % current_namespace)) def login(request): return HttpResponse("CMS登陆的首页")
urlpatterns = [ path('movie/',include([ path('',views.movie), path('list/',views.movie_list), ]
)) ]
# !/usr/bin/env python # -*- coding:utf-8 -*- # Project: DjangoURL # Software: PyCharm2018.3 # DateTime: 2018-11-16 14:06 # File: urls.py # __author__: 天晴天朗 # Email: tqtl@tqtl.org from django.urls import re_path from article import views urlpatterns = [ re_path(r'^$', views.article), re_path(r'^list/(?P<year>\d{4})/$', views.article_list), ]
实例代码以下:
views.py;
from django.shortcuts import render from django.shortcuts import redirect from django.shortcuts import reverse from django.http import HttpResponse # Create your views here. def index(request): """ 订单 :param request: :return: """ return HttpResponse("订单首页") def login(request): username = request.GET.get('username') if username: return HttpResponse('登陆页面') else: # login_url = reverse('login') detail_url = reverse('order_detail', kwargs={'order_id': 1}) return redirect(detail_url) def order_detail(request, order_id): """ 订单详情 :param request: :param order_id: :return: """ text = "您的订单号是:%s" % order_id return HttpResponse(text)
#!/usr/bin/env python # -*- coding:utf-8 -*- # Project: DjangoURL # Software: PyCharm2018.3 # DateTime: 2018-11-16 15:31 # File: converters.py # __author__: 天晴天朗 # Email: tqtl@tqtl.org from django.urls import register_converter class CategoryConverter(object): """ 自定义urls转换器:cate; """ # 正则规则必须为regex名称; regex = 'r\w+|(\w+\+\w+)+' def to_python(self, value): """ value:python + django + flask ['python','django','flask'] :param value: :return: """ result = value.split('+') return result def to_url(self, value): """ value:['python','django','flask'] python + django + flask :param value: :return: """ if isinstance(value, list): result = "+".join(value) return result else: raise RuntimeError('转换URL的时候,分类参数必须为列表形式!') register_converter(CategoryConverter, 'cate')
# 修改数据库链接为MySQL数据库; DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'DataGather', 'USER': 'root', 'PASSWORD': 'Tqtl911!@#)^', 'HOST': '127.0.0.1', 'PORT': '3306', } }
from django.db import models # Create your models here. class Book(models.Model): """书籍""" id = models.AutoField(primary_key=True) # 表明是一个主键; name = models.CharField(max_length=100, null=False, verbose_name='书籍名称') author = models.CharField(max_length=100, null=False, verbose_name='书籍做者') price = models.FloatField(null=False, default=0, verbose_name="书籍价格") class Publisher(models.Model): """出版社""" name = models.CharField(max_length=100, null=False) address = models.CharField(max_length=100, null=True)
from django.shortcuts import render from django.shortcuts import HttpResponse from .models import Book # Create your views here. def index(request): # 一、使用ORM添加一条数据到数据库中; book = Book(name='西游记', author='吴承恩', price='66') book.save() # 二、进行书籍的查询;get和filter方法以及first方法; book1 = Book.objects.get(pk=2) # 无论主键是id仍是nid,均可以; book2 = Book.objects.filter(name='西游记') # <QuerySet [<Book: <Book:(西游记,吴承恩,66.0)>>]> book2 = Book.objects.filter(name='西游记').first() # <Book:(西游记,吴承恩,66.0)> print(book2) print(book1) # 三、删除数据-delete方法; book3 = Book.objects.get(pk=5) book3.delete() # 四、修改数据:先查询出来,再从新赋值,最后save至数据库; book4 = Book.objects.get(pk=6) book4.price = 1993 book4.save()# 注意不要忘记save方法; return HttpResponse('书籍查询成功!')
Python 3.6.7 (v3.6.7:6ec5cf24b7, Oct 20 2018, 13:35:33) [MSC v.1900 64 bit (AMD64)] on win32 Django 2.1.3 import pytz from datetime import datetime now = datetime.now() now datetime.datetime(2018, 11, 29, 16, 33, 41, 110258) utc_timezone = pytz.timezone("UTC") now.astimezone(utc_timezone) datetime.datetime(2018, 11, 29, 8, 33, 41, 110258, tzinfo=<UTC>) now = now.re Traceback (most recent call last): File "<input>", line 1, in <module> AttributeError: 'datetime.datetime' object has no attribute 're' now = now.replace(day=22) now datetime.datetime(2018, 11, 22, 16, 33, 41, 110258) now = now.replace(tzinfo=pytz.timezon) Traceback (most recent call last): File "<input>", line 1, in <module> AttributeError: module 'pytz' has no attribute 'timezon' now = now.replace(tzinfo=pytz.timezon('Asia/Shanghai')) Traceback (most recent call last): File "<input>", line 1, in <module> AttributeError: module 'pytz' has no attribute 'timezon' now = now.replace(tzinfo=pytz.timezone('Asia/Shanghai')) now datetime.datetime(2018, 11, 22, 16, 33, 41, 110258, tzinfo=<DstTzInfo 'Asia/Shanghai' LMT+8:06:00 STD>)
若是USE_TZ设置为False,那么Django获取到的当前时间
定义def __str__(self):定义方法,return "<(Author id:%s,create_time:%s)>"%(self.id,self.create_time),能够在视图函数中打印具体对象;
56.1 on_delete= models.CASCADE级联操做;on_delete=
56.2 on_delelte = models.PROTECT;
56.3 on_delete = models.SET_NULL;可是字段自己为null;
56.4 on_delete = models,SET_DEFAULT;被删除后,指定默认值;
56.5 on_delete = models.SET(此处能够指定一个函数),null=True)
56.6 DO_NOTHING,不采起任何行动,一切全看数据库级别的约束;
on_delete = models.SET_DEFAULT,null =True,default = Category.objects.get(pk=4))
根据实际的业务进行指定以上两种类型;
驱动下载地址: https://dev.mysql.com/downloads/connector/j/
from django.shortcuts import render from django.http import HttpResponse # from .models import Article from .models import * # Create your views here. def index(request): # 一、id =1和 id__exact =1 二者等价; # article = Article.objects.filter(id__exact=1)# 二者等价! # article = Article.objects.filter(id=1) # 二者等价! # 二、 区分大小写和不区分大小写!涉及到MySQL数据库的排序规则;# 查看ORM翻译成的SQL语句,仅适用于filter语句中,get会报错! article = Article.objects.filter(title__exact='Hello World') # SELECT `article`.`id`, `article`.`title`, `article`.`content` FROM `article` WHERE `article`.`title` = Hello World # 三、None语句的查询; # article = Article.objects.filter(title__exact=None) # SELECT `article`.`id`, `article`.`title`, `article`.`content` FROM `article` WHERE `article`.`title` IS NULL # 四、忽略大小写的查询,好比exact和iexact; article = Article.objects.filter(title__iexact='HELLO WORLD') # SELECT `article`.`id`, `article`.`title`, `article`.`content` FROM `article` WHERE `article`.`title` LIKE HELLO WORLD print(article) print(article.query) return HttpResponse('查询成功!') """ 小结: 一、exact翻译成=; 二、iexact翻译成LIKE; """
from django.shortcuts import render from django.http import HttpResponse # from .models import Article from .models import * # Create your views here. # def index(request): # # 一、id =1和 id__exact =1 二者等价; # # article = Article.objects.filter(id__exact=1)# 二者等价! # # article = Article.objects.filter(id=1) # 二者等价! # # # 二、 区分大小写和不区分大小写!涉及到MySQL数据库的排序规则;# 查看ORM翻译成的SQL语句,仅适用于filter语句中,get会报错! # article = Article.objects.filter(title__exact='Hello World') # # SELECT `article`.`id`, `article`.`title`, `article`.`content` FROM `article` WHERE `article`.`title` = Hello World # # # 三、None语句的查询; # # article = Article.objects.filter(title__exact=None) # # SELECT `article`.`id`, `article`.`title`, `article`.`content` FROM `article` WHERE `article`.`title` IS NULL # # # 四、忽略大小写的查询,好比exact和iexact; # article = Article.objects.filter(title__iexact='HELLO WORLD') # # SELECT `article`.`id`, `article`.`title`, `article`.`content` FROM `article` WHERE `article`.`title` LIKE HELLO WORLD # print(article) # print(article.query) # return HttpResponse('查询成功!') """ 小结: 一、exact翻译成=; 二、iexact翻译成LIKE; """ def index1(request): article = Article.objects.filter(pk__exact=1) print(type(article)) print(article) print(article.query) """ <class 'django.db.models.query.QuerySet'> <QuerySet [<Article: Article object (1)>]> SELECT `article`.`id`, `article`.`title`, `article`.`content` FROM `article` WHERE `article`.`id` = 1 """ return HttpResponse('index1') def index2(request): # result = Article.objects.filter(title__contains='hello world') RESULT = Article.objects.filter(title__icontains='HELLO WORLD') print(RESULT) print(RESULT.query) """ 一、使用contains: <QuerySet []> SELECT `article`.`id`, `article`.`title`, `article`.`content` FROM `article` WHERE `article`.`title` LIKE BINARY %hello world% 二、使用icontains: <QuerySet [<Article: Article object (3)>]> SELECT `article`.`id`, `article`.`title`, `article`.`content` FROM `article` WHERE `article`.`title` LIKE %HELLO WORLD% """ return HttpResponse('contains&icontains的区别,好比LIKE和LIKE BINARY')
from django.db import models # Create your models here. class Article(models.Model): title = models.CharField(max_length=200) content = models.TextField() category = models.ForeignKey('Category',null=True, on_delete=models.CASCADE,related_name='article') class Meta: db_table = 'article' class Category(models.Model): name = models.CharField(max_length=128) class Meta: db_table = 'category'