python Django Basic Operation

Django commonly used commands

Create a Django project

Django-admin startprotect  mysite

 

After creating the project, the generated files

 

The outermost layer of the file: mysite / root directory is just a container of your project, Django does not care about its name, you can rename it to any name you like

manage.py: a variety of ways to let you use the command-line tool Django project management. Read: django-admin and manage.py get more details of manage.py

There is a layer of mysite / directory containing your project it is a pure python package. python package name is its name refer to it when you need to use anything inside (for example: mysite.urls)

mysite / __ init__.py: an empty folder, tell python this directory should be considered a python package 

mysite / settings.py: Django project configuration file. 

mysite / urls.py: URL statement Django project, as you site's "directory"

mysite / wsgi.py: Run your project as the entrance on WSGI compliant web server.

Modify the settings file the following line:

1. ALLOWED_HOSTS = [ '*'] is added to allow the host behind a corresponding increase or ip *

2. LANGUAGE_CODE = 'zh-Hans' language code to: zh-Hans

3. TIME_ZONE = 'Asia / Shanghai' will change the time zone Asia / Shanghai

4. USE_TZ = False False to

 

Creating App

python manage.py startapp polls

 

 After the app has been created, modify the settings file the following

 

 Modify the urls content (as the jump to use, easy to manage in the future)

 

NOTE: When to Use include

 

path的四个参数(两个必传,两个可选)
path参数: route
path参数:views
path参数:kwargs
path参数:name
创建完成以后,polls文件夹下面的内容为:

 

 

 创建urls.py文件,写以下图内容

 

写models文件

from django.db import models
# Create your models here.
class Question(models.Model):
  question_text = models.CharField(max_length=200)
  pub_date = models.DateTimeField('date published')
class Choice(models.Model):
  question = models.ForeignKey(Question, on_delete=models.CASCADE)
  choice_text = models.CharField(max_length=200)
  votes = models.IntegerField(default=0)

 

  

 生成models迁移文件

python manage.py makemigrations polls

 

 注:如果不写polls的话,为全部APP

把迁移文件写入数据库

python manage.py migrate

 

 进入shell环境:

python manage.py shell

通过模型类操作数据表

# 进入shell环境以后,首先导入模型
from polls.models import * # 导入全部模型
from django.utils import timezone  # 导入时间模块
# 创建方法一:
q = Question(question_text="什么地方的菜最有特色?", pub_date=timezone.now())
q.save()
# 关联创建,用问题关联创建选项
q.choice_set.create(choice_text="湖南")
# 创建方法二:
q = Question()      # 创建实例对象
q.question_text = "什么地方的菜最有特色?"
q.pub_date = timeaone.now()
q.save()
# 创建方法三:
Question.objects.create(question_text="什么地方的菜最有特色?",
pub_date=timezone.now())
运行项目(python manage.py runserver)
一、本机测试运行命令
二、本机做为主机运行命令(python manage.py runserver 0.0.0.0:8080# ***********************************************
# 修改方法一:
Question.objects.update(question_text = "什么地方最好玩?")
# 修改方法二:(这个方法不适合批量修改,只以最后一次保存为准,请谨慎使用)
q.question_text = "什么地方的菜最有特色?"
# ***********************************************
# 删除:(先查询到某个id的内容,然后用删除命令)
q = Question.objects.get(id=1)
q.delete()
# ***********************************************
# 查询
q = Question.objects.all()  # 查询全部
q = Question.objects.get(id=1)  # 查询指定的一个
Question.objects.filter(question_text__startswith='什么地方')  # 过滤查询,查询 以某某
开头的内容
q.choice_set.count()  # 查询跟本问题关联的选项的个数
Choice.objects.filter(question__pub_date__year=current_year)  # 查找问题发布日期为本年
的所有的选项
# 关联查询
q.choice_set.all()  # 查询跟这个问题关联的所有的选项

运行项目 (python manage.py runserver)

一、本机测试运行命令

# 在cmd命令行,cd进入项目所在目录,调试好当前项目所用的python环境,我这里用的py_data环境,使用
python manage.py runserver 命令
(py_data) D:\python\django\mysite>python manage.py  runserver

 

二、 本机做为主机运行命令 (python manage.py runserver 0.0.0.0:8080)

# 在cmd命令行,cd进入项目所在目录,调试好当前项目所用的python环境,我这里用的py_data环境,使用
python manage.py runserver 命令
(py_data) D:\python\django\mysite>python manage.py  runserver 0.0.0.0:8080

 编写views

往页面上渲染文字, 不做任何跳转, 用HttpResponse

from django.http import HttpResponse  # 导入django内置模块 HttpResponse
def index(request):
  """
 测试:只往网页上返回文字
 """
return HttpResponse("<h2>Hello World!!</h2>")  # 可以写入H5标签

用一个APP之间跳转使用render

from django.shortcuts import render  # 导入django内置模块render
def index(request):
  """
 测试:同一App之间的页面跳转
 context为字典形式,里面传入的内容为键值对形式,为需要往网页上面渲染的内容
 """
context = {}
return render(request, "polls/index.html", context)

不同app之间的页面跳转使用HttpResponseRedirect和reverse搭配使用

from django.http import HttpResponseRedirect
from django.urls import reverse
def login(request):
  """
 测试:登陆成功,跳转网站首页
 """
  info = dict(rquest.POST)
  '''判断登陆信息与数据库是否相同,如果相同做以下跳转'''
 return HttpResponseRedirect(reverse("index:index"))
  '''判断登陆信息与数据库如果不相同,做以下跳转'''
 return render(request, "polls/index.html", context={"message": "账号和密码不对,请
重新登陆"})

提取权限控制,get和post访问返回提示

from django.shortcuts import render
from django.http import HttpResponse
# 提取共同的方法,写成装饰器,在需要用到的地方,加上这个权限控制
# 访问页面如果用的是post请求,执行views里面加入装饰器的方法,
# 如果用的是get请求,返回没有权限浏览页面
def verify_control(fun):
  def verify_con(request):
    if request.method == 'POST':
      return fun(request)
    elif request.method == 'GET':
      return HttpResponse("你没有权限浏览该网页")
  return verify_con

接口写法,返回形式为json格式

from .models import *
import json
from .verify import *  # 导入写入的权限控制
import re
from django.shortcuts import render
from django.http import HttpResponse
@verify_control # 加入装饰器,如果用的get方式提交,则提示没有权限
def api_add_question(request):
  """
   测试:用接口的形式提交
   本接口为前端新建问题,用post提交数据
   需要用到的参数:{"question_text": "xxx","pub_date":"2019-01-17"}
 """
  info = dict(request.POST)
  try:
    Question.objects.get(question_text=info["question_text"][0])
  except Subject.DoesNotExist:
新建teamplates和static文件夹
teamplates(里面放的是网站的html文件)
static(里面放的是css,js ,图片,音乐,视频等一系列的文件)
注:teamplates下面新建app同名的目录,方便以后发布网站时,整理静态文件和html文件
    Question.objects.create(question_text=info["question_text"][0],
                pub_date=info["pub_date"][0])
    return HttpResponse(json.dumps({"message": "添加成功"}))
  else:
    return HttpResponse(json.dumps({"message": "该问题已经存在,不需要重添加"}))

 

新建teamplates和static文件夹

teamplates(里面放的是网站html文件)

 

static (里面放的css,js,图片,音乐,视频等一系列的文件)

 

 

注意!!!:teamplates下面新建app同名的目录,方便以后发布网站时,整理静态文件和html文件

 

Guess you like

Origin www.cnblogs.com/haozong/p/11235809.html