Django入门笔记(二)_补充说明

命令行

# 查看版本
python -m django --version

# 获取路径
python -c "import django; print(django.__path__)"

# 创建项目
django-admin startproject mysite

# 创建app
django-admin startapp polls
python manage.py startapp polls

# 运行服务器
python manage.py runserver

# 指定端口运行服务器
python manage.py runserver 8080

# 监听所有公网 IP,0是0.0.0.0的快捷方式
python manage.py runserver 0:8000

# 默认主页
http://127.0.0.1:8000/

# 根据INSTALLED_APPS列表,对应生成数据库迁移文件migrations
python manage.py makemigrations

# 指定APP构建迁移文件
python manage.py makemigrations polls

# 迁移前返回对应的APP的SQL语句
python manage.py sqlmigrate polls 0001

# 跟踪特殊表django_migrations推断未被迁移的文件,执行迁移文件内容
python manage.py migrate

# 执行测试
python manage.py test

# 进入项目交互模式
python manage.py shell

# 创建超级用户
python manage.py createsuperuser

Django的类与函数

  • from django.db import models
# 用户类不需要自己创建,导入即可
from django.contrib.auth.models import User

# 不可变字段,固定为创建时时间
models.DateTimeField(auto_now_add=True)

# 字段可为空
updated_at = models.DateTimeField(null=True)

# 重命名外键API,代替了topics_set
models.ForeignKey(related_name='topics')

# 不需要使用外键
models.ForeignKey(related_name='+')

# 最大字符串长度及唯一字段
models.CharField(max_length=30, unique=True)
  • from django.conf.urls import url, include
# 创建url
url(r'admin/', admin.site.urls),

# 导入其他urls.py
url(r'polls/', include('polls.urls'))
  • from django.shortcuts import render, get_object_or_404
# 与html交互,返回HttpResponse
render(request,'polls.html',{'context':context})

# 尝试获取对象,否则返回404
get_object_or_404(Question,pk=question_id)
  • from django.http import HttpResponse, HttpResponseRedirect, Http404
# 生成HttpResponse对象
HttpResponse('Holle world')

# 重定向,返回HttpResponse
HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

# 抛出404异常
raise Http404("Question does not exist")
  • from django.template import loader
# 指定模板
template = loader.get_template('polls/index.html')
HttpResponse(template.render(context, request))
  • from django.urls import reverse, resolve
# 获取url
url = reverse('polls:results',args=(1,))

# 获取视图
view = resolve('/polls/results/1/')
  • from django.test import TestCase
class ResultsTests(TestCase):
	self.assertIs(response.status_code,200)
	self.assertEqual(response.status_code,200)
	self.assertEquals(response.status_code,200)

    self.assertContains(response,'empty')
    self.assertQuerysetEqual(response.context['questions'],[])	
  • from django.utils import timezone
# 当前时区现在时间
now = timezone.now()

模板语法

{% load static %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">

<a href="{% url 'polls:question_list' %}">question_list</a>

{% if error_message %}
{{ error_message }}
{% endif %}

<!-- 生成cookies -->
{% csrf_token %}
 
<ul>
{% for choice in question.choice.all %}
    <li> {{ forloop.counter }} </li>
{% endfor %}
</ul>

使用其他数据库

  • mysql8.0需修改加密方式为’mysql_native_password’
use mysql;
select user,plugin from user where user='root';
alter user 'root'@'localhost' identified with mysql_native_password by 'password';
flush privileges; #生效
  • 安装链接包
pip install mysqlclient
# pip install wordloud
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydatabase',
        'USER': 'mydatabaseuser',
        'PASSWORD': 'mypassword',
        'HOST': '127.0.0.1',
        'PORT': '3306',
        # 取消外键检查
        'OPTIONS':{
        "init_command":"SET foreign_key_checks = 0;",
        }        
    }
}

API交互

  • python manage.py shell
import django
from polls.models import Question, Choice
from django.utils import timezone

# 查看django版本
django.get_version()

# 配置django
django.setup()

# 在指定表创建实例对象
q = Question(question_text="What's new?", pub_date=timezone.now()); q.save()
q = Question.objects.create(question_text="What's new?", pub_date=timezone.now())

# 字段取值
q.id
q.pk #效果同上
q.question_text
q.pub_date

# 更新值
q.question_text = "What's up"
q.save()

# 列出数据库表中所有对象
Question.objects.all()

# 排序
Question.objects.order_by('pub_date')[:5] #升序
Question.objects.order_by('-pub_date')[:5]	#降序
Question.objects.order_by('pub_date').reverse() #降序

# 获取数量
Question.objects.count()

# 取实例对象
Question.objects.get(id=1)
Question.objects.get(pk=1) #效果同上
Question.objects.get(question_text="What's up")

# 过滤实例对象
# 关键字参数自动调用其关联函数,双用下划线来分隔
Question.objects.filter(question_text__startswith='What')[0]

# 获取所有行值列表
list(Question.objects.all().values())

# 创建外键关联对象
q.choice.create(choice_text='Not much', votes=0)
q.choice.create(choice_text='The sky', votes=0)
c = q.choice.create(choice_text='Just hacking again', votes=0)

# 根据关联对象获取主键对象
c.question

# 显示所有外键关联对象
q.choice.all()
q.choice.count()

# 删除对象
c = q.choice.filter(choice_text__startswith='Just hacking')
c.delete()

# 使用response正常情况下不可用的附加属性,如response.context
from django.test.utils import setup_test_environment
setup_test_environment()

# 创建一个 Client 实例
from django.test import Client
client = Client()

其他常用

from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
import json
import decimal

# 判断用户登录
request.user.is_authenticated

# 获取当前用户username
request.user

# 获取挡墙请求方式
if request.method == 'POST'# 获取请求参数
request.GET.get('choice')
request.GET.getlist('choices')
request.POST.get('choice')
request.POST.getlist('choices')

# json格式返回字典
return JsonResponse(dt)

# 列表json格式返回列表
return JsonResponse(ls, safe=False)

# 重定向,返回HttpResponse
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

# 返回自定义json格式
class DecimalEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, decimal.Decimal):
            return float(obj)
        if isinstance(obj,date):
            return obj.strftime('%Y%m%d')
        return super(DecimalEncoder, self).default(obj)
        
rs_mks = json.dumps(rs_mks, cls=DecimalEncoder, ensure_ascii=False)
return HttpResponse(rs_mks, content_type="application/json,charset=utf-8")


# 获取静态文件字符串,可用于ajax
response = render(request, 'tbd_ajax.html', locals())
content = response.content.decode('utf-8')
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值