安装django
pip install django==2.2
建一个在线商城的项目
django-admin startproject pyshop
启动项目
python manage.py runserver
页面访问效果 http://127.0.0.1:8000
建议一个项目的app 产品 products
django-admin startapp products
在app的 views 里面写一下 请求页面 比如 http://127.0.0.1:8000/products
from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse('HelloWorld')
为了让 products能够访问 需要在app的urls(需要自己建) 及 项目的urls配置urlpatterns
app的url配置:
from django.urls import path from . import views urlpatterns = [ path('', views.index), ]
项目的url配置 他要包括app的url 组合起来用
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('products/', include('products.urls')), ]
展示效果http://127.0.0.1:8000/products/
模型 对product 进行模型设计 实际上就是建表(python会按照模型建好的自己建表)
from django.db import models # Create your models here. class Product(models.Model): name = models.CharField(max_length=255) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField(max_length=2083)
在setting 加上 app的配置
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'products.apps.ProductsConfig', ]
创建product的model
python manage.py makemigrations
(venv) D:\PyShop>python manage.py makemigrations Migrations for 'products': products\migrations\0001_initial.py - Create model Product (venv) D:\PyShop>
初始化的文件放在这里 products\migrations\0001_initial.py
根据生产的 初始化文件建表
python manage.py migrate
(venv) D:\PyShop>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, products, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying products.0001_initial... OK Applying sessions.0001_initial... OK (venv) D:\PyShop>
类似的 再建一个 offer的模型 包含 优惠券的代码 描述 和折扣
class Offer(models.Model): code = models.CharField(max_length=10) description = models.CharField(max_length=256) discount = models.FloatField() 同样去做迁移变化 (venv) D:\PyShop>python manage.py makemigrations Migrations for 'products': products\migrations\0002_offer.py - Create model Offer (venv) D:\PyShop> 再去生成表 (venv) D:\PyShop>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, products, sessions Running migrations: Applying products.0002_offer... OK (venv) D:\PyShop>
创建超级管理员 admin
(venv) D:\PyShop>python manage.py createsuperuser Username (leave blank to use 'work1'): admin Email address: dfwlai@163.com Password: Password (again): The password is too similar to the username. This password is too short. It must contain at least 8 characters. This password is too common. Bypass password validation and create user anyway? [y/N]: y Superuser created successfully. (venv) D:\PyShop>
在admin.py中注册我们的模型
from django.contrib import admin from .models import Product # Register your models here. admin.site.register(Product)
admin页面会显示如下
可以手动增加一个产品 橘子
展示效果如下
这个时候我们改一下 让产品字段按列表展出
from django.contrib import admin from .models import Product # Register your models here. class ProductAdmin(admin.ModelAdmin): list_display = ('name','price','stock') admin.site.register(Product,ProductAdmin)
效果
1、报错:
File "D:\Python\Python37-32\lib\site-packages\django\views\debug.py", line 332, in get_traceback_html
t = DEBUG_ENGINE.from_string(fh.read())
UnicodeDecodeError: 'gbk' codec can't decode byte 0xa6 in position 9737: illegal multibyte sequence
解决:
打开django/views下的debug.py文件,转到line331行:
with Path(CURRENT_DIR, 'templates', 'technical_500.html').open() as fh
将其改成:
with Path(CURRENT_DIR, 'templates', 'technical_500.html').open(encoding="utf-8") as fh
就成功了。
3、django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install mysqlclient?
pip install PyMySQL pymsql 已经不用了
pip install mysqlclient 安装mysqlclient
wiki:
使用mysql 来当数据库1、首先默认的setting的数据库配置
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
改为: 其中lzy 是database名字 我的本地库 root没有密码
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'lzy',
'HOST': '127.0.0.1',
'PORT': 3306,
'USER': 'root',
'PASSWORD': '',
}
}