pip list
pip freeze
pip install django==1.8.2
import django
django.get_version()
python manage.py startapp booktest
from django.db import models
class BookInfo(models.Model):
btitle = models.CharField(max_length=20)
bpub_date = models.DateTimeField()
def _ _str_ _(self):
return "%d" % self.pk
class HeroInfo(models.Model):
hname = models.CharField(max_length=20)
hgender = models.BooleanField()
hcontent = models.CharField(max_length=100)
hBook = models.ForeignKey('BookInfo')
def _ _str_ _(self):
return "%d" % self.pk
python manage.py makemigrations
python manage.py migrate
python manage.py shell
from booktest.models import BookInfo,HeroInfo
from django.utils import timezone
from datetime import *
BookInfo.objects.all()
b = BookInfo()
b.btitle="射雕英雄传"
b.bpub_date=datetime(year=1990,month=1,day=10)
b.save()
b=BookInfo.objects.get(pk=1)
b
b.id
b.btitle
b.btitle=u"天龙八部"
b.save()
b.delete()
h=HeroInfo()
h.htitle=u'郭靖'
h.hgender=True
h.hcontent=u'降龙十八掌'
h.hBook=b
h.save()
b.heroinfo_set.all()
h=b.heroinfo_set.create(htitle=u'黄蓉',hgender=False,hcontent=u'打狗棍法')
h
python manage.py runserver ip:port
python manage.py runserver 8080
python manage.py createsuperuser,按提示输入用户名、邮箱、密码
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'
from django.contrib import admin
from models import BookInfo
admin.site.register(BookInfo)
class QuestionAdmin(admin.ModelAdmin):
...
admin.site.register(Question, QuestionAdmin)
list_display = ['pk', 'btitle', 'bpub_date']
list_filter = ['btitle']
search_fields = ['btitle']
list_per_page = 10
fields = ['bpub_date', 'btitle']
fieldsets = [
('basic',{'fields': ['btitle']}),
('more', {'fields': ['bpub_date']}),
]
对于HeroInfo模型类,有两种注册方式
按照BookInfor的注册方式完成HeroInfo的注册
from django.contrib import admin
from models import BookInfo,HeroInfo
class HeroInfoInline(admin.StackedInline):
model = HeroInfo
extra = 2
class BookInfoAdmin(admin.ModelAdmin):
inlines = [HeroInfoInline]
admin.site.register(BookInfo, BookInfoAdmin)
class HeroInfoInline(admin.TabularInline)
def gender(self):
if self.hgender:
return '男'
else:
return '女'
gender.short_description = '性别'
class HeroInfoAdmin(admin.ModelAdmin):
list_display = ['id', 'hname', 'gender', 'hcontent']
#coding:utf-8
from django.http import HttpResponse
def index(request):
return HttpResponse("index")
def detail(request,id):
return HttpResponse("detail %s" % id)
url(r'^', include('booktest.urls')),
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index),
url(r'^([0-9]+)/$', views.detail),
]
'DIRS': [os.path.join(BASE_DIR, 'templates')],
{{输出值,可以是变量,也可以是对象.属性}}
{%执行代码段%}
首页
图书列表
{%for book in booklist%}
-
{{book.btitle}}
{%endfor%}
详细页
{{book.btitle}}
{%for hero in book.heroinfo_set.all%}
- {{hero.hname}}---{{hero.hcontent}}
{%endfor%}
from django.http import HttpResponse
from django.template import RequestContext, loader
from models import BookInfo
def index(request):
booklist = BookInfo.objects.all()
template = loader.get_template('booktest/index.html')
context = RequestContext(request, {'booklist': booklist})
return HttpResponse(template.render(context))
def detail(reqeust, id):
book = BookInfo.objects.get(pk=id)
template = loader.get_template('booktest/detail.html')
context = RequestContext(reqeust, {'book': book})
return HttpResponse(template.render(context))
url(r'^book/([0-9]+)/$', views.detail),
url(r'^admin/', include(admin.site.urls, namespace='booktest')),
url(r'^book/([0-9]+)/$', views.detail, name="detail"),
from django.shortcuts import render
from models import BookInfo
def index(reqeust):
booklist = BookInfo.objects.all()
return render(reqeust, 'booktest/index.html', {'booklist': booklist})
def detail(reqeust, id):
book = BookInfo.objects.get(pk=id)
return render(reqeust, 'booktest/detail.html', {'book': book})
pip install mysql-python
create databases test2 charset=utf8
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test2',
'USER': '用户名',
'PASSWORD': '密码',
'HOST': '数据库服务器ip,本地可以使用localhost',
'PORT': '端口,默认为3306',
}
}
python manage.py inspectdb > booktest/models.py
bookinfo.heroinfo_set
heroinfo.bookinfo
heroinfo.book_id
_
class BookInfo(models.Model):
...
class Meta():
ordering = ['id']
class BookInfo(models.Model):
...
class Meta():
ordering = ['-id']
class BookInfo(models.Model):
btitle = models.CharField(max_length=20)
bpub_date = models.DateTimeField()
bread = models.IntegerField(default=0)
bcommet = models.IntegerField(default=0)
isDelete = models.BooleanField(default=False)
class HeroInfo(models.Model):
hname = models.CharField(max_length=20)
hgender = models.BooleanField(default=True)
isDelete = models.BooleanField(default=False)
hcontent = models.CharField(max_length=100)
hbook = models.ForeignKey('BookInfo')
insert into booktest_bookinfo(btitle,bpub_date,bread,bcommet,isDelete) values
('射雕英雄传','1980-5-1',12,34,0),
('天龙八部','1986-7-24',36,40,0),
('笑傲江湖','1995-12-24',20,80,0),
('雪山飞狐','1987-11-11',58,24,0)
insert into booktest_heroinfo(hname,hgender,hbook_id,hcontent,isDelete) values
('郭靖',1,1,'降龙十八掌',0),
('黄蓉',0,1,'打狗棍法',0),
('黄药师',1,1,'弹指神通',0),
('欧阳锋',1,1,'蛤蟆功',0),
('梅超风',0,1,'九阴白骨爪',0),
('乔峰',1,2,'降龙十八掌',0),
('段誉',1,2,'六脉神剑',0),
('虚竹',1,2,'天山六阳掌',0),
('王语嫣',0,2,'神仙姐姐',0),
('令狐冲',1,3,'独孤九剑',0),
('任盈盈',0,3,'弹琴',0),
('岳不群',1,3,'华山剑法',0),
('东方不败',0,3,'葵花宝典',0),
('胡斐',1,4,'胡家刀法',0),
('苗若兰',0,4,'黄衣',0),
('程灵素',0,4,'医术',0),
('袁紫衣',0,4,'六合拳',0)
class BookInfo(models.Model):
...
books = models.Manager()
class BookInfoManager(models.Manager):
def get_queryset(self):
return super(BookInfoManager, self).get_queryset().filter(isDelete=False)
class BookInfo(models.Model):
...
books = BookInfoManager()
class BookInfo(models.Model):
...
@classmethod
def create(cls, title, pub_date):
book = cls(btitle=title, bpub_date=pub_date)
book.bread=0
book.bcommet=0
book.isDelete = False
return book
引入时间包:from datetime import *
调用:book=BookInfo.create("hello",datetime(1980,10,11));
保存:book.save()
class BookInfoManager(models.Manager):
def create_book(self, title, pub_date):
book = self.model()
book.btitle = title
book.bpub_date = pub_date
book.bread=0
book.bcommet=0
book.isDelete = False
return book
class BookInfo(models.Model):
...
books = BookInfoManager()
调用:book=BookInfo.books.create_book("abc",datetime(1980,1,1))
保存:book.save()
class BookInfoManager(models.Manager):
def create_book(self, title, pub_date):
book = self.create(btitle = title,bpub_date = pub_date,bread=0,bcommet=0,isDelete = False)
return book
class BookInfo(models.Model):
...
books = BookInfoManager()
调用:book=Book.books.create_book("abc",datetime(1980,1,1))
查看:book.pk
filter(键1=值1,键2=值2)
等价于
filter(键1=值1).filter(键2=值2)
print([e.title for e in Entry.objects.all()])
print([e.title for e in Entry.objects.all()])
querylist=Entry.objects.all()
print([e.title for e in querylist])
print([e.title for e in querylist])
filter(isDelete=False)
exclude(btitle__contains='传')
exclude(btitle__endswith='传')
filter(btitle__isnull=False)
filter(pk__in=[1, 2, 3, 4, 5])
filter(id__gt=3)
filter(bpub_date__year=1980)
filter(bpub_date__gt=date(1980, 12, 31))
filter(heroinfo_ _hcontent_ _contains='八')
filter(pk__lt=6)
from django.db.models import Max
maxDate = list.aggregate(Max('bpub_date'))
count = list.count()
list.filter(bread__gte=F('bcommet'))
list.filter(bread__gte=F('bcommet') * 2)
list.filter(isDelete=F('heroinfo__isDelete'))
list.filter(bpub_date__lt=F('bpub_date') + timedelta(days=1))
from django.db.models import Q
list.filter(Q(pk_ _lt=6))
list.filter(pk_ _lt=6).filter(bcommet_ _gt=10)
list.filter(Q(pk_ _lt=6) | Q(bcommet_ _gt=10))
list.filter(~Q(pk__lt=6))
class AreaInfo(models.Model):
atitle = models.CharField(max_length=20)
aParent = models.ForeignKey('self', null=True, blank=True)
上级对象:area.aParent
下级对象:area.areainfo_set.all()
from models import AreaInfo
def area(request):
area = AreaInfo.objects.get(pk=130100)
return render(request, 'booktest/area.html', {'area': area})
地区
当前地区:{{area.atitle}}
上级地区:{{area.aParent.atitle}}
下级地区:
{ %for a in area.areainfo_set.all%}
- {{a.atitle}}
{ %endfor%}
urlpatterns = [
url(r'^area/$', views.area, name='area')
]
http://www.itcast.cn/python/1/?i=1&p=new,只匹配“/python/1/”部分
url(r'^([0-9]+)/$', views.detail, name='detail'),
url(r'^(?P[0-9]+)/$', views.detail, name='detail'),
from django.conf.urls import include, url
urlpatterns = [
url(r'^', include('booktest.urls', namespace='booktest')),
]
请求http://www.itcast.cn/booktest/1/
在sesstings.py中的配置:
url(r'^booktest/', include('booktest.urls', namespace='booktest')),
在booktest应用urls.py中的配置
url(r'^([0-9]+)/$', views.detail, name='detail'),
匹配部分是:/booktest/1/
匹配过程:在settings.py中与“booktest/”成功,再用“1/”与booktest应用的urls匹配
新建views1.py
#coding:utf-8
from django.http import HttpResponse
def index(request):
return HttpResponse("你好")
在urls.py中修改配置
from . import views1
url(r'^$', views1.index, name='index'),
找不到了
{{request_path}}
DEBUG = False
ALLOWED_HOSTS = ['*', ]
http://127.0.0.1:8000/test/
dict.get('键',default)
或简写为
dict['键']
dict.getlist('键',default)
def getTest1(request):
return render(request,'booktest/getTest1.html')
def getTest2(request):
return render(request,'booktest/getTest2.html')
def getTest3(request):
return render(request,'booktest/getTest3.html')
url(r'^getTest1/$', views.getTest1),
url(r'^getTest2/$', views.getTest2),
url(r'^getTest3/$', views.getTest3),
Title
链接1:一个键传递一个值
gettest2
链接2:一个键传递多个值
gettest3
def getTest2(request):
a=request.GET['a']
b=request.GET['b']
context={'a':a,'b':b}
return render(request,'booktest/getTest2.html',context)
Title
a:{{ a }}
b:{{ b }}
def getTest3(request):
a=request.GET.getlist('a')
b=request.GET['b']
context={'a':a,'b':b}
return render(request,'booktest/getTest3.html',context)
Title
a:{% for item in a %}
{{ item }}
{% endfor %}
b:{{ b }}
def postTest1(request):
return render(request,'booktest/postTest1.html')
url(r'^postTest1$',views.postTest1)
Title
def postTest2(request):
uname=request.POST['uname']
upwd=request.POST['upwd']
ugender=request.POST['ugender']
uhobby=request.POST.getlist('uhobby')
context={'uname':uname,'upwd':upwd,'ugender':ugender,'uhobby':uhobby}
return render(request,'booktest/postTest2.html',context)
url(r'^postTest2$',views.postTest2)
Title
{{ uname }}
{{ upwd }}
{{ ugender }}
{{ uhobby }}
#coding=utf-8
from django.http import HttpResponse
def index(request):
return HttpResponse('你好')
from django.http import HttpResponse
from django.template import RequestContext, loader
def index(request):
t1 = loader.get_template('polls/index.html')
context = RequestContext(request, {'h1': 'hello'})
return HttpResponse(t1.render(context))
from django.http import HttpResponse
from datetime import *
def index(request):
response = HttpResponse()
if request.COOKIES.has_key('h1'):
response.write('' + request.COOKIES['h1'] + '
')
response.set_cookie('h1', '你好', 120)
# response.set_cookie('h1', '你好', None, datetime(2016, 10, 31))
return response
在views1.py中
from django.http import HttpResponse,HttpResponseRedirect
def index(request):
return HttpResponseRedirect('js/')
def index2(request,id):
return HttpResponse(id)
在应用的urls.py中增加一个url对象
url(r'^([0-9]+)/$', views1.index2, name='index2'),
from django.core.urlresolvers import reverse
def index(request):
return HttpResponseRedirect(reverse('booktest:index2', args=(1,)))
from django.http import JsonResponse
def index2(requeset):
return JsonResponse({'list': 'abc'})
from django.shortcuts import render
def index(request):
return render(request, 'booktest/index.html', {'h1': 'hello'})
from django.shortcuts import redirect
from django.core.urlresolvers import reverse
def index(request):
return redirect(reverse('booktest:index2'))
from django.shortcuts import *
def detail(request, id):
try:
book = get_object_or_404(BookInfo, pk=id)
except BookInfo.MultipleObjectsReturned:
book = None
return render(request, 'booktest/detail.html', {'book': book})
将settings.py中的DEBUG改为False
将请求地址输入2和100查看效果
from django.shortcuts import *
def index(request):
# list = get_list_or_404(BookInfo, pk__lt=1)
list = get_list_or_404(BookInfo, pk__lt=6)
return render(request, 'booktest/index.html', {'list': list})
将settings.py中的DEBUG改为False
项INSTALLED_APPS列表中添加:
'django.contrib.sessions',
项MIDDLEWARE_CLASSES列表中添加:
'django.contrib.sessions.middleware.SessionMiddleware',
from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse
def index(request):
uname = request.session.get('uname')
return render(request, 'booktest/index.html', {'uname': uname})
def login(request):
return render(request, 'booktest/login.html')
def login_handle(request):
request.session['uname'] = request.POST['uname']
return redirect(reverse('main:index'))
def logout(request):
# request.session['uname'] = None
# del request.session['uname']
# request.session.clear()
request.session.flush()
return redirect(reverse('main:index'))
主url:
from django.conf.urls import include, url
urlpatterns = [
url(r'^', include('booktest.urls', namespace='main'))
]
应用url:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'login/$', views.login, name='login'),
url(r'login_handle/$', views.login_handle, name='login_handle'),
url(r'logout/$', views.logout, name='logout')
]
首页
你好:{{uname}}
登录
退出
登录
def login_handle(request):
request.session['uname'] = request.POST['uname']
# request.session.set_expiry(10)
# request.session.set_expiry(timedelta(days=5))
# request.session.set_expiry(0)
# request.session.set_expiry(None)
return redirect(reverse('main:index'))
SESSION_ENGINE='django.contrib.sessions.backends.db'
SESSION_ENGINE='django.contrib.sessions.backends.cache'
SESSION_ENGINE='django.contrib.sessions.backends.cached_db'
pip install django-redis-sessions
SESSION_ENGINE = 'redis_sessions.session'
SESSION_REDIS_HOST = 'localhost'
SESSION_REDIS_PORT = 6379
SESSION_REDIS_DB = 0
SESSION_REDIS_PASSWORD = ''
SESSION_REDIS_PREFIX = 'session'
启动:sudo redis-server /etc/redis/redis.conf
停止:sudo redis-server stop
重启:sudo redis-server restart
redis-cli:使用客户端连接服务器
keys *:查看所有的键
get name:获取指定键的值
del name:删除指定名称的键
DIRS=[os.path.join(BASE_DIR,"templates")]
loader.get_template(template_name),返回一个Template对象
Template对象的render(RequestContext)方法,使用context渲染模板
from django.template import loader, RequestContext
from django.http import HttpResponse
def index(request):
tem = loader.get_template('temtest/index.html')
context = RequestContext(request, {})
return HttpResponse(tem.render(context))
from django.shortcuts import render
def index(request):
return render(request, 'temtest/index.html')
{{ variable }}
from django.db import models
class HeroInfo(models.Model):
...
def showName(self):
return self.hname
from django.shortcuts import render
from models import *
def index(request):
hero = HeroInfo(hname='abc')
context = {'hero': hero}
return render(request, 'temtest/detail.html', context)
{{hero.showName}}
{ %for ... in ...%}
循环逻辑
{{forloop.counter}}表示当前是第几次循环
{ %empty%}
给出的列表为或列表不存在时,执行此处
{ %endfor%}
{ %if ...%}
逻辑1
{ %elif ...%}
逻辑2
{ %else%}
逻辑3
{ %endif%}
{ % comment % }
多行注释
{ % endcomment % }
{ %include "foo/bar.html" % }
{ % url 'name' p1 p2 %}
{ % csrf_token %}
if list1|length > 1
name|lower|upper
list|join:", "
value|default:"什么也没有"
value|date:'Y-m-d'
{#...#}
{# { % if foo % }bar{ % else % } #}
{ %block block_name%}
这里可以定义默认值
如果不定义默认值,则表示空字符串
{ %endblock%}
{ % extends "base.html" %}
{ %block block_name%}
实际填充内容
{ %endblock%}
{ % block block_name %}
区域内容
{ % endblock block_name %}
{%block title%}{%endblock%} 水果超市
top--{{logo}}
{%block left%}{%endblock%}
{%block content%}{%endblock%}
bottom
{%extends 'temtest/base.html'%}
{%block title%}商品{%endblock%}
{%block left%}
goods left
{%endblock%}
{%extends 'temtest/base.html'%}
{%block title%}用户中心{%endblock%}
{%block left%}
user left
{%endblock%}
{%extends 'temtest/base.html'%}
{%block content%}
首页内容
{%endblock content%}
{%extends 'temtest/base_goods.html'%}
{%block content%}
商品正文列表
{%endblock content%}
{%extends 'temtest/base_user.html'%}
{%block content%}
用户密码修改
{%endblock content%}
logo='welcome to itcast'
def index(request):
return render(request, 'temtest/index.html', {'logo': logo})
def goodslist(request):
return render(request, 'temtest/goodslist.html', {'logo': logo})
def userpwd(request):
return render(request, 'temtest/userpwd.html', {'logo': logo})
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^list/$', views.goodslist, name='list'),
url(r'^pwd/$', views.userpwd, name='pwd'),
]
视图代码:
def index(request):
return render(request, 'temtest/index2.html',
{
't1': 'hello
'
})
模板代码:
{{t1}}
< 会转换为<
> 会转换为>
' (单引号) 会转换为'
" (双引号)会转换为 "
& 会转换为 &
{{t1|escape}}
{{ data|safe }}
{ % autoescape off %}
{{ body }}
{ % endautoescape %}
{ { data|default:"123" }}
{ { data|default:"<b>123</b>" }}
def csrf1(request):
return render(request,'booktest/csrf1.html')
def csrf2(request):
uname=request.POST['uname']
return render(request,'booktest/csrf2.html',{'uname':uname})
url(r'^csrf1/$', views.csrf1),
url(r'^csrf2/$', views.csrf2),
Title
Title
{{ uname }}
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def csrf2(request):
uname=request.POST['uname']
return render(request,'booktest/csrf2.html',{'uname':uname})
ImageFont表示字体对象,ubuntu的字体路径为“/usr/share/fonts/truetype/freefont”
代码如下:
from django.http import HttpResponse
def verifycode(request):
#引入绘图模块
from PIL import Image, ImageDraw, ImageFont
#引入随机函数模块
import random
#定义变量,用于画面的背景色、宽、高
bgcolor = (random.randrange(20, 100), random.randrange(
20, 100), 255)
width = 100
height = 25
#创建画面对象
im = Image.new('RGB', (width, height), bgcolor)
#创建画笔对象
draw = ImageDraw.Draw(im)
#调用画笔的point()函数绘制噪点
for i in range(0, 100):
xy = (random.randrange(0, width), random.randrange(0, height))
fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
draw.point(xy, fill=fill)
#定义验证码的备选值
str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
#随机选取4个值作为验证码
rand_str = ''
for i in range(0, 4):
rand_str += str1[random.randrange(0, len(str1))]
#构造字体对象
font = ImageFont.truetype('FreeMono.ttf', 23)
#构造字体颜色
fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
#绘制4个字
draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
#释放画笔
del draw
#存入session,用于做进一步验证
request.session['verifycode'] = rand_str
#内存文件操作
import cStringIO
buf = cStringIO.StringIO()
#将图片保存在内存中,文件类型为png
im.save(buf, 'png')
#将内存中的图片数据返回给客户端,MIME类型为图片png
return HttpResponse(buf.getvalue(), 'image/png')
from . import viewsUtil
urlpatterns = [
url(r'^verifycode/$', viewsUtil.verifycode),
]
看不清,换一个
from django.http import HttpResponse
def verifycodeValid(request):
vc = request.POST['vc']
if vc.upper() == request.session['verifycode']:
return HttpResponse('ok')
else:
return HttpResponse('no')
urlpatterns = [
url(r'^verifycodeValid/$', views.verifycodeValid),
]
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
mysite/static/myapp/
/static/my_app/myexample.jpg
{ % load static from staticfiles %}
from django.http import HttpResponse
class MyException():
def process_exception(request,response, exception):
return HttpResponse(exception.message)
MIDDLEWARE_CLASSES = (
'test1.myexception.MyException',
...
)
pic=models.ImageField(upload_to='cars/')
pip install Pillow==3.4.1
MEDIA_ROOT=os.path.join(BASE_DIR,"static/media")
文件上传
from django.conf import settings
def upload(request):
if request.method == "POST":
f1 = request.FILES['pic']
fname = '%s/cars/%s' % (settings.MEDIA_ROOT,f1.name)
with open(fname, 'w') as pic:
for c in f1.chunks():
pic.write(c)
return HttpResponse("ok")
else:
return HttpResponse("error")
python manage.py createsuperuser
然后按提示填写用户名、邮箱、密码
from django.contrib import admin
from models import *
admin.site.register(HeroInfo)
class HeroAdmin(admin.ModelAdmin):
...
admin.site.register(HeroInfo,HeroAdmin)
@admin.register(HeroInfo)
class HeroAdmin(admin.ModelAdmin):
class HeroAdmin(admin.ModelAdmin):
actions_on_top = True
actions_on_bottom = True
在models.py文件中
from django.db import models
from tinymce.models import HTMLField
from django.utils.html import format_html
class HeroInfo(models.Model):
hname = models.CharField(max_length=10)
hcontent = HTMLField()
isDelete = models.BooleanField()
def hContent(self):
return format_html(self.hcontent)
在admin.py文件中
class HeroAdmin(admin.ModelAdmin):
list_display = ['hname', 'hContent']
在models.py中HeroInfo类的代码改为如下:
def hContent(self):
return format_html(self.hcontent)
hContent.admin_order_field = 'hname'
在models.py中为HeroInfo类增加方法hName:
def hName(self):
return self.hname
hName.short_description = '姓名'
hContent.short_description = '内容'
在admin.py页中注册
class HeroAdmin(admin.ModelAdmin):
list_display = ['hName', 'hContent']
class HeroAdmin(admin.ModelAdmin):
...
list_filter = ['hname', 'hcontent']
class HeroAdmin(admin.ModelAdmin):
...
list_per_page = 10
class HeroAdmin(admin.ModelAdmin):
...
search_fields = ['hname']
class HeroAdmin(admin.ModelAdmin):
...
fields = [('hname', 'hcontent')]
class HeroAdmin(admin.ModelAdmin):
...
fieldsets = (
('base', {'fields': ('hname')}),
('other', {'fields': ('hcontent')})
)
class HeroInline(admin.TabularInline):
model = HeroInfo
class BookAdmin(admin.ModelAdmin):
inlines = [
HeroInline,
]
'DIRS': [os.path.join(BASE_DIR, 'templates')],
from django.core.paginator import Paginator
def pagTest(request, pIndex):
list1 = AreaInfo.objects.filter(aParent__isnull=True)
p = Paginator(list1, 10)
if pIndex == '':
pIndex = '1'
pIndex = int(pIndex)
list2 = p.page(pIndex)
plist = p.page_range
return render(request, 'booktest/pagTest.html', {'list': list2, 'plist': plist, 'pIndex': pIndex})
url(r'^pag(?P[0-9]*)/$', views.pagTest, name='pagTest'),
{%for area in list%}
- {{area.id}}--{{area.atitle}}
{%endfor%}
{%for pindex in plist%}
{%if pIndex == pindex%}
{{pindex}}
{%else%}
{{pindex}}
{%endif%}
{%endfor%}
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
class AreaInfo(models.Model):
aid = models.IntegerField(primary_key=True)
atitle = models.CharField(max_length=20)
aPArea = models.ForeignKey('AreaInfo', null=True)
python manage.py makemigrations
python manage.py migrate
from django.shortcuts import render
from django.http import JsonResponse
from models import AreaInfo
def index(request):
return render(request, 'ct1/index.html')
def getArea1(request):
list = AreaInfo.objects.filter(aPArea__isnull=True)
list2 = []
for a in list:
list2.append([a.aid, a.atitle])
return JsonResponse({'data': list2})
def getArea2(request, pid):
list = AreaInfo.objects.filter(aPArea_id=pid)
list2 = []
for a in list:
list2.append({'id': a.aid, 'title': a.atitle})
return JsonResponse({'data': list2})
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index),
url(r'^area1/$', views.getArea1),
url(r'^([0-9]+)/$', views.getArea2),
]
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^', include('ct1.urls', namespace='ct1')),
url(r'^admin/', include(admin.site.urls)),
]
'DIRS': [os.path.join(BASE_DIR, 'templates')],
省市区列表
tar zxvf django-tinymce-2.4.0.tar.gz
python setup.py install
INSTALLED_APPS = (
...
'tinymce',
)
TINYMCE_DEFAULT_CONFIG = {
'theme': 'advanced',
'width': 600,
'height': 400,
}
urlpatterns = [
...
url(r'^tinymce/', include('tinymce.urls')),
]
from django.db import models
from tinymce.models import HTMLField
class HeroInfo(models.Model):
...
hcontent = HTMLField()
def editor(request):
return render(request, 'other/editor.html')
urlpatterns = [
...
url(r'^editor/$', views.editor, name='editor'),
]
def content(request):
hname = request.POST['hname']
hcontent = request.POST['hcontent']
heroinfo = HeroInfo.objects.get(pk=1)
heroinfo.hname = hname
heroinfo.hcontent = hcontent
heroinfo.save()
return render(request, 'other/content.html', {'hero': heroinfo})
urlpatterns = [
...
url(r'^content/$', views.content, name='content'),
]
姓名:{{hero.hname}}
{%autoescape off%}
{{hero.hcontent}}
{%endautoescape%}
CACHES={
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 60,
}
}
安装包:pip install django-redis-cache
CACHES = {
"default": {
"BACKEND": "redis_cache.cache.RedisCache",
"LOCATION": "localhost:6379",
'TIMEOUT': 60,
},
}
连接:redis-cli
切换数据库:select 1
查看键:keys *
查看值:get 键
from django.views.decorators.cache import cache_page
@cache_page(60 * 15)
def index(request):
return HttpResponse('hello1')
#return HttpResponse('hello2')
{% load cache %}
{% cache 500 hello %}
hello1
{% endcache %}
from django.core.cache import cache
设置:cache.set(键,值,有效时间)
获取:cache.get(键)
删除:cache.delete(键)
清空:cache.clear()
pip install django-haystack
pip install whoosh
pip install jieba
INSTALLED_APPS = (
...
'haystack',
)
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.whoosh_cn_backend.WhooshEngine',
'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
}
}
#自动生成索引
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
urlpatterns = [
...
url(r'^search/', include('haystack.urls')),
]
# coding=utf-8
from haystack import indexes
from models import GoodsInfo
class GoodsInfoIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
def get_model(self):
return GoodsInfo
def index_queryset(self, using=None):
return self.get_model().objects.all()
#goodsinfo_text.txt,这里列出了要对哪些列的内容进行检索
{{ object.gName }}
{{ object.gSubName }}
{{ object.gDes }}
{% if query %}
搜索结果如下:
{% for result in page.object_list %}
{{ result.object.gName }}
{% empty %}
啥也没找到
{% endfor %}
{% if page.has_previous or page.has_next %}
{% if page.has_previous %}{% endif %}« 上一页{% if page.has_previous %}{% endif %}
|
{% if page.has_next %}{% endif %}下一页 »{% if page.has_next %}{% endif %}
{% endif %}
{% endif %}
import jieba
from whoosh.analysis import Tokenizer, Token
class ChineseTokenizer(Tokenizer):
def __call__(self, value, positions=False, chars=False,
keeporiginal=False, removestops=True,
start_pos=0, start_char=0, mode='', **kwargs):
t = Token(positions, chars, removestops=removestops, mode=mode,
**kwargs)
seglist = jieba.cut(value, cut_all=True)
for w in seglist:
t.original = t.text = w
t.boost = 1.0
if positions:
t.pos = start_pos + value.find(w)
if chars:
t.startchar = start_char + value.find(w)
t.endchar = start_char + value.find(w) + len(w)
yield t
def ChineseAnalyzer():
return ChineseTokenizer()
from .ChineseAnalyzer import ChineseAnalyzer
查找
analyzer=StemmingAnalyzer()
改为
analyzer=ChineseAnalyzer()
python manage.py rebuild_index
celery==3.1.25
celery-with-redis==3.0
django-celery==3.1.17
INSTALLED_APPS = (
...
'djcelery',
}
...
import djcelery
djcelery.setup_loader()
BROKER_URL = 'redis://127.0.0.1:6379/0'
CELERY_IMPORTS = ('应用名称.task')
import time
from celery import task
@task
def sayhello():
print('hello ...')
time.sleep(2)
print('world ...')
python manage.py migrate
sudo redis-server /etc/redis/redis.conf
python manage.py celery worker --loglevel=info
function.delay(parameters)
#from task import *
def sayhello(request):
print('hello ...')
import time
time.sleep(10)
print('world ...')
# sayhello.delay()
return HttpResponse("hello world")
pip freeze > plist.txt
sudo apt-get install python-virtualenv
sudo easy_install virtualenvwrapper
mkvirtualenv [虚拟环境名称]
workon [虚拟环境名称]
pip install -r plist.txt
DEBUG = False
ALLOW_HOSTS=['*',]表示可以访问服务器的ip
pip install uwsgi
[uwsgi]
socket=外网ip:端口(使用nginx连接时,使用socket)
http=外网ip:端口(直接做web服务器,使用http)
chdir=项目根目录
wsgi-file=项目中wsgi.py文件的目录,相对于项目根目录
processes=4
threads=2
master=True
pidfile=uwsgi.pid
daemonize=uswgi.log
sudo apt-get nginx
解压缩:
tar zxvf nginx-1.6.3.tar.gz
进入nginx-1.6.3目录依次执行如下命令进行安装:
./configure
make
sudo make install
sudo conf/nginx.conf
在server下添加新的location项,指向uwsgi的ip与端口
location / {
include uwsgi_params;将所有的参数转到uwsgi下
uwsgi_pass uwsgi的ip与端口;
}
location /static {
alias /var/www/test5/static/;
}
sudo chmod 777 /var/www/test5
mkdir static
STATIC_ROOT='/var/www/test5/static/'
STATIC_URL='/static/'
sudo apt-get install git
git
ssh-keygen -t rsa -C "[email protected]"
git clone [email protected]:账号名/项目名.git
git pull
git push origin master
mkdir test7
cd test7
git init
git add 文件1 文件2 ...
git add 目录
git checkout -- 文件名
git status
git commit -m '本次提交的说明信息'
当前版本的历史版本:git log
简版显示:git log --pretty=oneline
历史命令:git reflog
在Git中,用HEAD表示当前版本,也就是最新的提交3628164...882e1e0(注意我的提交ID和你的肯定不一样),上一个版本就是HEAD^,上上一个版本就是HEAD^^,当然往上100个版本写100个^比较容易数不过来,所以写成HEAD~100
对比工作区和仓库区中某版本某文件的不同
git diff HEAD -- 文件名
git reset HEAD^或版本号
rm 文件名
git rm 文件名
git commit -m '说明信息'