Django框架搭建

 

1.搭建Django框架

Eclipse/STS

         https://spring.io/tools3/sts/legacy

Python SDK

         https://www.python.org/getit/

pip安装

若scripts目录为空:

         python -m ensurepip 创建出pip3.exe

         python -m pip install --upgrade pip --force-reinstall 安装更新

Django安装

         pip install Django

 

2.配置步骤

见操作

 

3.HELLOWORLD

A.创建视图

MVC框架中的VIEW,创建view.py

from django.http import HttpResponse

 

def hello(request):

    return HttpResponse("Helloworld!")

B.在urls.py文件中添加映射

from . import view

from hellodj.login import login

 

urlpatterns = [

    path('访问路径/', 文件名.函数名)

    path('hello/', view.hello),

    path('login/', login),

]

 

 

4.MYSQL驱动

 

3.4及以下版本:

pip install MySQLdb

 

 Could not find a version that satisfies the requirement MySQLdb (from

 

versions: )No matching distribution found for MySQLdb

 

3.5及以上版本:

 

PyMySQL 下载地址:https://github.com/PyMySQL/PyMySQL。

 

C:\Users\Administrator\AppData\Local\Programs\Python\Python38\Scripts

$ pip3 install PyMySQL

 

https://www.runoob.com/python3/python3-mysql.html

 

中文处理:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb4 in position 106:

 

invalid start byte

 

访问权限

pymysql.err.OperationalError: (1045, "Access denied for user

 

'test'@'localhost' (using password: YES)")

 

#ip+user+pwd+dbname

    db = pymysql.connect("localhost","root","","test" )

sql = "select * from users where id="+id

 

类型转换

TypeError: can only concatenate str (not "int") to str

 

#sql = "select * from users where id="+id

sql = "select * from users where id="+str(id)

 

print ("Database version : %s " % data)

TypeError: not all arguments converted during string formatting

 

<class 'tuple'>: (1, 'hello', 'world', 1, 'aa')

 

#print ("username : %s " % data)

print ("username : %s " % data[n])

 

https://www.runoob.com/python/python-tuples.html

print ("username : %s " % str(data[0:]))

 

5.修改TEMPLATES

TEMPLATES = [

    {

        'BACKEND': 'django.template.backends.django.DjangoTemplates',

        'DIRS': [],

        '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',

            ],

        },

    },

]

 

TEMPLATES = [

    {

        'BACKEND': 'django.template.backends.django.DjangoTemplates',

        'DIRS': [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',

            ],

        },

    },

]

 

引包

# -*- coding:utf-8 -*-

from django.shortcuts import render

 

6.模型

DATABASES = {

    'default': {

        'ENGINE': 'django.db.backends.sqlite3',

        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),

    }

}

 

DATABASES = {

    'default': {

#         'ENGINE': 'django.db.backends.sqlite3',

#         'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),

        'ENGINE': 'django.db.backends.mysql',  # 或者使用

 

mysql.connector.django

        'NAME': 'test',

        'USER': 'root',

        'PASSWORD': '',

        'HOST':'localhost',

        'PORT':'3306',

    }

}

 

创建MODEL

C:\Users\Administrator\AppData\Local\Programs\Python\Python38\Scripts

django-admin startapp D:\workspace-sts-3.9.12.RELEASE\hellodj\TestModel

 

可能的错误:

CommandError: 'D:\workspace-sts-3.9.12.RELEASE\hellodj\TestModel' is not a

 

valid

 app name. Please make sure the name is a valid identifier.

 

正确的语句:

D:\workspace-sts-3.9.12.RELEASE\hellodj>C:\Users\Administrator\AppData

 

\Local\Programs\Python\Python38\Scripts\django-admin.exe startapp TestModel

 

7.添加APP

INSTALLED_APPS = [

    'django.contrib.admin',

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.messages',

    'django.contrib.staticfiles',

]

 

改为:

INSTALLED_APPS = [

    'django.contrib.admin',

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.messages',

    'django.contrib.staticfiles',

    'TestModel',# 添加此项

]

 

反向生成:

D:\workspace-sts-3.9.12.RELEASE\hellodj>c:\Users\Administrator\AppData

 

\Local\Programs\Python\Python38\python.exe manage.py inspectdb

 

可能的错误:

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.

Did you install mysqlclient?

 

安装

pip install mysqlclient

 

D:\workspace-sts-3.9.12.RELEASE\hellodj>c:\Users\Administrator\AppData

 

\Local\Pro

grams\Python\Python38\python.exe manage.py inspectdb >models.py

(根目录)

 

 

 

 

 

发布了39 篇原创文章 · 获赞 38 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/FRESHET/article/details/105660137
今日推荐