course 1
- django install
- django-admin startproject jstest
- django-admin startapp blog
- vim settings.py
app add-----> blog - vim urls.py
url(r'^blog/index/$', 'blog.views.index'), - vim blog.views.py
from django.http import HttpResponse
def index(req):
return HttpResponse("<h1>Hello World!</h1>") - python manager.py runserver
url default is 127.0.0.1:8000
course 2
- set url (3 ways)
- url(r'^blog/index/$', 'blog.views.index'),
- from blog.views import index
url(r'^blog/index/$', index), - urlpatterns = patterns('blog.views',
url(r'^blog/index/$', 'index'),
)
- url content
- set special parameter
# urls.py url(r'^blog/index/(?P<id>\d{2})/$', 'blog.views.index'), # blog.views.py def index(request, id):
- set not special parameter, you can use parameter with arbitrary name in the views file, e.g: param
# urls.py url(r'^blog/index/(\d{2})/$', 'blog.views.index'), # blog.views.py def index(request, param):
- set special parameter
course 3
- render to response html (3 ways)
- use raw html code
# blog.views.py from django.http import HttpResponse def index(req): return HttpResponse("<h1>hello World</h1>")
- render html file
create teplate object with two ways, loader a html file; create template with string.# blog.views.py from django.http import HttpResponse from django.template import loader, Context, Template def index(req): t = loader.get_template('index.html') # loader a html file to create template object t = Template("<h1>{{param}}</h1>") # create template with string c = Context({'param': 'jshan'}) return HttpResponse(t.render(c))
- render html file shortcuts(recommendation)
# blog.views.py from django.shortcuts import render_to_response def index(req): return render_to_response('index.html', {'param': 'jshan'})
- use raw html code
course 4
- teplate parameters
We can have many types, e.g normal parameter(str, int, float, bool), dictionary, class object(include normal attribute, function(without parameters)), list. And the parsing of parameters in html file is also with the above priority.index.html
<h1>hello {{name}}</h1> <h1>hello {{user.name}}</h1> <h1>hello {{User.name}}</h1> <h1>hello {{User.sayname}}</h1> <h1>hello {{namelist.0}}</h1>
course 5
- template tags
Use the tags in html file. E.g if else endif# if {% if user %} <li>name: {{user}}</li> {% else %} <li>no user</li> {% endif %} # for {% for name in name_list %} <li>{{name}}</li> {% endfor %} {% for k,v in name_dict.items %} <li>name: {{k}}, age: {{v}}</li> {% endfor %}
course 6
-
models in pyton
We can connect mysql with python.- service mysqld start
- service mysqld status
- create database csvt default charset = utf8;
- set set.py DATABASE info of django project
- create and record some models in models.py
- python manage.py syncdb
-
how to create models records (3 ways)
# create instance -> set some attribute -> call save function emp = Employee() emp.name = 'jshan' emp.save() # create instance with attribute -> call save function emp = Employee(name='jshan') emp.save() # create object instance to create record emp = Employee.objects.create(name='jshan')
In order to make the content more friendly, we can set the appointed 'unicode' function.
# example class Employee(models.Model): name = models.CharField(max_length=20) def __unicode__(self): return self.name
course 7
-
create many to one model
We can create model which has foreign key model. For example an author has many books, and set one book belong to only one author.# author class Author(models.Model): name = CharField(max_length=20) def __unicode__(self): return self.name # book class Book(model.Model): name = CharField(max_length=20) author = ForeighKey(Author) def __unicode__(self): return self.name
If we want to get a author's all books info, we can use 'author.book_set.all()' command; if we cant to get a book's author info, we can use 'book.author' or 'book.author_id'.
-
create many to many model
We can create model which has many filed. For example an author has many books, and a book also belongs to many authors.# author class Author(models.Model): name = CharField(max_length=20) def __unicode__(self): return self.name # book class Book(models.Model): name = CharField(max_length=20) authors = ManyToManyField(Author)
course 8 form 表单的操作
blog.model.py
class Users(models.Model):
name = models.CharField(max_length=20, verbose_name=u"用户名")
headImg = models.FileField(upload_to="./upload/") # 这里是相对路径,默认是相对该工程而言的,这里的相对可以在 settings.py 中的 MEDIA_ROOT 修改指定
def __unicode__(self):
return self.name
blog.vies.py
from django import forms
from django.http import HttpResponse
from django.shortcuts import render_to_response
### 创建表单的方法1
class UserForm(forms.Form):
name = forms.CharField()
headImg = forms.FileField() # 用于上传文件使用
### 创建表单的方法2
from django.forms import ModelForm
from blog.models import Users
class UserForm(ModelForm):
class Meta:
model = Users
fields = ('name', 'headImg')
def register(req):
if req.method == 'POST':
form = UserForm(req.POST, req.FILES) # 绑定表单动作,还包括文件时需要使用request.FILES
if form.is_valid(): # 验证表单的字段的有效性
print form.cleaned_data['name']
# 保存文件 form.cleaned_data['headImg'] 是一个 UploadedFile 对象
fp = file('/upload/' + form.cleaned_data['headImg'].name, 'wb')
s = form.cleaned_data['headImg'].read()
fp.write(s)
fp.close()
# 或者是保存在数据库中
user = User()
user.username = form.cleaned_data['username']
user.headImg = form.cleaned_data['headImg']
user.save()
return HttpResponse('ok')
else:
form = UserForm()
return render_to_response('register.html', {'form': form})
## register.html
<form method="post" enctype="multipart/form-data">
{{form}}
<input type="submit" value="ok" />
</form>
如果出现 csrf 错误,这是由于站点跳转的异常导致的,可以在settings.py中将 MIDDLEWARE_CLASSES中的 'django.middleware.csrf.CsrfViewMiddleware' 进行注释
regist login index整个流程的操作
from django.http import HttpResponseRedirect
def login(req):
if req.method == "POST":
uf = UserForm(req.POST)
if uf.is_valid():
username = uf.cleaned_data['username']
password = uf.cleaned_data['password']
user = User.object.filter(username__exact=username, password__exact=password)
if user:
r_response = HttpResponseRedirect('/index/')
r_response.set_cookie('username', username, 3600)
return r_response
else:
return HttpResponseRedirect('/login/')
else:
uf = UserForm()
return render_to_response('login.html', {'uf': uf})
set cookie 当我们在登录跳转的过程中,我们需要获取到上一个页面的内容
r_response = HttpResponseRedirect('/index/')
r_response.set_cookie('username', username, 3600)
def index(req):
username = req.COOKIES.get('username', '')
return render_to_response('index.html', {'username': username})
- 设置cookie的方法:
r_response = HttpResponseRedirect('/index/')
r_response.set_cookie('username', username)
return r_response - 查询cookie的方法:
username = request.COOKIES.get('username', '') - 删除cookie的方法:
r_response = HttpResponse('logout')
r_response.delete_cookie('username')
return r_response
sessions 的使用
为了保证数据的安全性,我们不宜直接使用COOKIES来操作数据,这是就可以使用sessions
settings.py 中需要打开 MIDDLEWARE_CLASSES中的 'django.contrib.sessions.middleware.SessionMiddleWare'
INSTALLED_APPS 中打开 'django.contrib.sessions'
同步db的时候会产生 django_session 表设置session的方法
req.session['username'] = username
在数据库 django_session 表里会有数据出现,并且值是加密过的,在浏览器前端里也不是明文信息查询session的方法
req.session.get('username', 'nobody')删除session的方法
del req.session['username']
django的用户管理系统
settings.py 打开INSTALLED_APPS 里面的 'django.contrib.auth'
那么在 syncdb 的时候,数据库中会创建 auth_ 开头的一些表
当然为了在后台查看,需要打开 'django.contrib.admin' 然后同步数据库后,会有 django_admin_log 表