命令行
python - m django - - version
python - c "import django; print(django.__path__)"
django- admin startproject mysite
django- admin startapp polls
python manage. py startapp polls
python manage. py runserver
python manage. py runserver 8080
python manage. py runserver 0 : 8000
http: // 127.0 .0 .1 : 8000 /
python manage. py makemigrations
python manage. py makemigrations polls
python manage. py sqlmigrate polls 0001
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 )
models. ForeignKey( related_name= 'topics' )
models. ForeignKey( related_name= '+' )
models. CharField( max_length= 30 , unique= True )
from django.conf.urls import url, include
url( r'admin/' , admin. site. urls) ,
url( r'polls/' , include( 'polls.urls' ) )
from django.shortcuts import render, get_object_or_404
render( request, 'polls.html' , { 'context' : context} )
get_object_or_404( Question, pk= question_id)
from django.http import HttpResponse, HttpResponseRedirect, Http404
HttpResponse( 'Holle world' )
HttpResponseRedirect( reverse( 'polls:results' , args= ( question. id , ) ) )
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 = 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 %}
{% 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
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交互
import django
from polls. models import Question, Choice
from django. utils import timezone
django. get_version( )
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( )
from django. test. utils import setup_test_environment
setup_test_environment( )
from django. test import Client
client = Client( )
其他常用
from django. http import HttpResponse, HttpResponseRedirect, JsonResponse
import json
import decimal
request. user. is_authenticated
request. user
if request. method == 'POST' :
request. GET. get( 'choice' )
request. GET. getlist( 'choices' )
request. POST. get( 'choice' )
request. POST. getlist( 'choices' )
return JsonResponse( dt)
return JsonResponse( ls, safe= False )
return HttpResponseRedirect( reverse( 'polls:results' , args= ( question. id , ) ) )
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" )
response = render( request, 'tbd_ajax.html' , locals ( ) )
content = response. content. decode( 'utf-8' )