django--基础操作

Django基础操作

django常用命令

  • 创建django项目
django-admin startproject mysite

创建项目完成以后,文件目录结构为:

修改settings文件内容

ALLOWED_HOSTS = ["*"]   # 允许的主机后面加 * 或者加对应的IP
LANGUAGE_CODE = 'zh-Hans'  # 语言编码改为zh-Hans
TIME_ZONE = 'Asia/Shanghai'  # 时区必变  Asia/Shanghai
USE_TZ = False  # 改为False伊娃
  • 创建APP 
python manage.py startapp polls

app创建完成以后,修改settings文件以下内容

 

修改mysite文件夹下urls内容(作为跳转使用,方便以后管理)

注:何时使用include

# path的四个参数(两个必传,两个可选)

# path参数: route
# path参数:views
# path参数:kwargs
# path参数:name

创建完APP以后,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

  

注:如果不写APP名字的话,为全部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())

# ***********************************************

# 修改方法一:
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:pythondjangomysite>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:pythondjangomysite>python manage.py  runserver 0.0.0.0:8080

  

  • 编写views

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

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之间的页面跳转使用HttResponseRedirect和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:
        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文件  

原文地址:https://www.cnblogs.com/donghaiming/p/10644960.html