@Gebitang
2015-05-08T09:42:31.000000Z
字数 29078
阅读 1759
django
my.ini
under unzip location
[mysqld]
basedir = D:\\dev\\mysql-5.6.24-winx64
datadir = D:\\userDATA\\mysqldata
datadir
folder. D:\dev\mysql-5.6.24-winx64\bin
to PATH
. mysqld --console
mysqladmin -u root shutdown
By default, there is no password for root user.
pip install Django
check import django
, print(django.get_version()
django-admin startproject prjname
django-admin startapp appname
url(r'^blog/index', 'blog.views.index'),
from django.http import HttpResponse
def index(req):
return HttpResponse('content')
python manager.py runserver
# Create your views here.
'''
from django.http import HttpResponse
from django.template import loader, Context
def index(req):
t = loader.get_template('index.html')
c = Context({})
return HttpResponse(t.render({c}))
'''
from django.shortcuts import render_to_response
def index(req):
return render_to_response('index.html',{} )
#code in views.py
class Person(object):
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
#mustn't have parameters
def say(self):
love = ' LOVES'
return self.name + love + ' Sharon.'
from django.shortcuts import render_to_response
def index(req):
#user = {'name':'Joehcin', 'age':32, 'sex':'male'}
user = Person('Joehcin', 32, 'Male')
book_list = ['python', 'java', 'php', 'go']
return render_to_response('index.html',{'title':'Gebitang page', 'user':user,'book_list':book_list} )
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" class="">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>{{title}}</title>
</head>
<body >
<h1>Hello {{user.name}}</h1>
<li>age: {{user.age}}</li>
<li>sex: {{user.sex}}</li>
<li>{{book_list.0}}</li>
<li>{{book_list.1}}</li>
<li>{{book_list.2}}</li>
<li>{{book_list.3}}</li>
<p>
<div>{{user.name}} say: {{user.say}}</div>
</body>
</html>
There is priority for them
Normal basic parameter
dictionary
object property
object method (the method mustn't have any parameter)
list
[04-25]
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" class="">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>{{title}}</title>
</head>
<body >
{% if user %}
<li>name: {{user.name}}</li>
{% else %}
用户不存在
{% endif %}
{% for book in book_list %}
<li>{{book}}</li>
{% endfor %}
{% for k, v in user.items %}
<li>{{forloop.revcounter}}: {{k}}:{{v}}</li>
{% endfor %}
</body>
</html>
from django.shortcuts import render_to_response
def index(req):
user = {'name':'Joehcin', 'age':32, 'sex':'male'}
# 'Person' object is not iterable
#user = Person('Joehcin', 32, 'Male')
book_list = ['python', 'java', 'C++', 'go']
return render_to_response('index.html',{'title':'Gebitang page', 'user':user,'book_list':book_list} )
Built-in tags and filters
in The template layer [04-25]
from django.conf.urls import include, url
from django.contrib import admin
from blog.views import index
urlpatterns = [
# Examples:
# url(r'^$', 'gebitang.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
#url(r'^blog/index/\d{2}$',index),
url(r'^blog/index/(\d{2})/$',index),
#P must be upcase. P for parameters, can be empty
# so (?P<id>\d{2}) will be like (\d{2}).
# both need to define parameter in index method.
# if the name is defined in url, the parameter name must be the same one in mehtod
# if the name is empty in url, then anyone would work
]
def index(req, parm):
user = {'name':'Joehcin', 'age':69, 'sex':'male'}
# 'Person' object is not iterable
#user = Person('Joehcin', 32, 'Male')
book_list = ['python', 'java', 'C++', 'go']
return render_to_response('index.html',{'title':'Gebitang page', 'user':user,'book_list':book_list, 'id':parm} )
PS: the following config don't work in django 1.8 version
# no module defaults found
from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns('blog.views',
url(r'^blog/index/$', 'index'),
)
[04-26]
# Create your views here.
from django.template import loader, Context, Template
from django.http import HttpResponse
def index(req):
t = loader.get_template('index.html')
c = Context({'uname':'Sharon My Love'})
return HttpResponse(t.render(c))
# directly create template
def index1(req):
t = Template('<h1>hello {{uname}}</h1')
c = Context({'uname':'Lee'})
return HttpResponse(t.render(c))
from django.shortcuts import render_to_response
def index2(req):
return render_to_response('index.html', {'uname':'Lee'})
Use ipython to check
install ipython pip install ipython
pyreadline is right choose in Windows OS.
this will be an interactive way with colorful lines.
Use admin site
official doc dev version
1.8 version for admin
or Just execute command: python manager.py syscdb
to set admin info.
[04-27]
import MySQLdb
and no errors.
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog', #this is new created apps
)
mysql -u root -p
; create database blog default charset=utf8;
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', #django.db.backends.mysql
'NAME': 'blog',
'USER':'root',
'PASSWORD':'123456',
'Host':'',
'PORT':'3306',
}
}
from django.db import models
# Create your models here.
class Employee(models.Model):
name = models.CharField(max_length=20)
manage.py syncdb
#Your models have changes that are not yet reflected in a migration, and so won't be applied.
#Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.
manage.py makemigrations
Migrations for 'blog':
0001_initial.py:
- Create model Employee
manage.py migrate
Operations to perform:
Synchronize unmigrated apps: staticfiles, messages
Apply all migrations: admin, blog, contenttypes, auth, sessions
Synchronizing apps without migrations:
Creating tables...
Running deferred SQL...
Installing custom SQL...
Running migrations:
Rendering model states... DONE
Applying blog.0001_initial... OK
manage.py check
to check whether there is any error. show databases; use blog; show tables; desc blog_employee;
[04-28]
- Three ways to create Object:
from blog.models import Employee
#1
emp = Employee()
emp.name = 'Joechin'
emp.save()
#2
emp = Employee(name='Sharon')
emp.save()
#4
emp = Employee.objects.create(name='Lee')
##find all
emps = Employee.objects.all()
[<Employee: Employee object>, <Employee: Employee object>, <Employee: E
mployee object>, <Employee: Employee object>]
from django.db import models
# Create your models here.
class Employee(models.Model):
name = models.CharField(max_length=20)
#this method will be called while find all objects. such as Employee.objecs.all()
def __unicode__(self):
return self.name
from blog.models import Employee
from django.shortcuts import render_to_response
#use database
def index(req):
emps = Employee.objects.all()
return render_to_response('index.html', {'emps':emps})
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" class="">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>{{title}}</title>
</head>
<body >
{{emps}}
{%for emp in emps %}
<div>{{forloop.counter}} {{emp}}</div>
{% endfor %}
<div>Total: {{emps|length}}</div>
</body>
</html>
[04-28] evening
from django.db import models
class Entry(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
class Blog(models.Model):
name = models.CharField(max_length=30)
entry = models.ForeignKey(Entry)
def __unicode__(self):
return self.name
manage.py makemigrations
; manage.py migrate
to create tables
use blog;
show tables; # blog_blog and blog_entry tables will be displayed.
desc blog_blog;
[04-30]
Official Docs
manage.py doc
from django.db import models
sex_choices = (
('f', 'famale'),
('m', 'male'),
)
class User(models.Model):
name = models.CharField(max_length=30)
sex = models.CharField(max_length=1, choices = sex_choices)
def __unicode__(self):
return self.name
manage.py makemigrations
, then run manage.py migrate
admin.py
under app folder, content is:
from django.contrib import admin
from blog.models import User
admin.site.register(User)
manage.py runserver
to surf you admin site:)[05-01]
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
class Book(models.Model):
name = models.CharField(max_length=30)
authors = models.ManyToManyField(Author)
def __unicode__(self):
return self.name
manage.py makemigrations
, manage.py migrate
manage.py shell
to interactively operate database
In [6]: Author.objects.create(name='Chinwe')
Out[6]: <Author: Chinwe>
In [7]: authors = Author.objects.all()
In [8]: authors
Out[8]: [<Author: Joechin>, <Author: Sharon>, <Author: Lee>, <Author: Chinwe>]
In [9]: b1 = Book()
In [10]: b1.name = 'python book1'
In [11]: b1.save()
In [12]: alen = Author.objecsts.get(name_exact='Joechin')
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-12-f742a45024c4> in <module>()
----> 1 alen = Author.objecsts.get(name_exact='Joechin')
AttributeError: type object 'Author' has no attribute 'objecsts'
In [13]: alen = Author.objects.get(name_exact='Joechin')
---------------------------------------------------------------------------
FieldError Traceback (most recent call last)
<ipython-input-13-d9e5576e1bca> in <module>()
----> 1 alen = Author.objects.get(name_exact='Joechin')
D:\Python279\lib\site-packages\django\db\models\manager.pyc in manager_method(se
lf, *args, **kwargs)
125 def create_method(name, method):
126 def manager_method(self, *args, **kwargs):
--> 127 return getattr(self.get_queryset(), name)(*args, **kwarg
s)
128 manager_method.__name__ = method.__name__
129 manager_method.__doc__ = method.__doc__
D:\Python279\lib\site-packages\django\db\models\query.pyc in get(self, *args, **
kwargs)
323 keyword arguments.
324 """
--> 325 clone = self.filter(*args, **kwargs)
326 if self.query.can_filter():
327 clone = clone.order_by()
D:\Python279\lib\site-packages\django\db\models\query.pyc in filter(self, *args,
**kwargs)
677 set.
678 """
--> 679 return self._filter_or_exclude(False, *args, **kwargs)
680
681 def exclude(self, *args, **kwargs):
D:\Python279\lib\site-packages\django\db\models\query.pyc in _filter_or_exclude(
self, negate, *args, **kwargs)
695 clone.query.add_q(~Q(*args, **kwargs))
696 else:
--> 697 clone.query.add_q(Q(*args, **kwargs))
698 return clone
699
D:\Python279\lib\site-packages\django\db\models\sql\query.pyc in add_q(self, q_o
bject)
1299 existing_inner = set(
1300 (a for a in self.alias_map if self.alias_map[a].join_type ==
INNER))
-> 1301 clause, require_inner = self._add_q(where_part, self.used_aliase
s)
1302 self.where.add(clause, AND)
1303 for hp in having_parts:
D:\Python279\lib\site-packages\django\db\models\sql\query.pyc in _add_q(self, q_
object, used_aliases, branch_negated, current_negated, allow_joins)
1326 child_clause, needed_inner = self.build_filter(
1327 child, can_reuse=used_aliases, branch_negated=branch
_negated,
-> 1328 current_negated=current_negated, connector=connector
, allow_joins=allow_joins)
1329 joinpromoter.add_votes(needed_inner)
1330 target_clause.add(child_clause, connector)
D:\Python279\lib\site-packages\django\db\models\sql\query.pyc in build_filter(se
lf, filter_expr, branch_negated, current_negated, can_reuse, connector, allow_jo
ins)
1142 if not arg:
1143 raise FieldError("Cannot parse keyword query %r" % arg)
-> 1144 lookups, parts, reffed_aggregate = self.solve_lookup_type(arg)
1145 if not allow_joins and len(parts) > 1:
1146 raise FieldError("Joined field references are not permitted
in this query")
D:\Python279\lib\site-packages\django\db\models\sql\query.pyc in solve_lookup_ty
pe(self, lookup)
1028 if aggregate:
1029 return aggregate_lookups, (), aggregate
-> 1030 _, field, _, lookup_parts = self.names_to_path(lookup_splitted,
self.get_meta())
1031 field_parts = lookup_splitted[0:len(lookup_splitted) - len(looku
p_parts)]
1032 if len(lookup_parts) == 0:
D:\Python279\lib\site-packages\django\db\models\sql\query.pyc in names_to_path(s
elf, names, opts, allow_many, fail_on_missing)
1384 available = sorted(field_names + list(self.annotatio
n_select))
1385 raise FieldError("Cannot resolve keyword %r into fie
ld. "
-> 1386 "Choices are: %s" % (name, ", ".joi
n(available)))
1387 break
1388 # Check if we need any joins for concrete inheritance cases
(the
FieldError: Cannot resolve keyword 'name_exact' into field. Choices are: book, i
d, name
In [14]: clear
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-14-05cac50f47bd> in <module>()
----> 1 clear
NameError: name 'clear' is not defined
In [15]: clean
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-15-175388b0347c> in <module>()
----> 1 clean
NameError: name 'clean' is not defined
In [16]: alen = Author.objects.get(name='Joechin')
In [17]: alen
Out[17]: <Author: Joechin>
In [18]: joechin = Author.objects.get(name='Joechin')
In [19]: joechin
Out[19]: <Author: Joechin>
In [20]: b1.authors.add(joechin)
In [21]: b1
Out[21]: <Book: python book1>
In [22]: b1.authors.add(authors[1])
In [23]: b1.authors.all
Out[23]: <bound method ManyRelatedManager.all of <django.db.models.fields.relate
d.ManyRelatedManager object at 0x037A89F0>>
In [24]: b1.authors.all()
Out[24]: [<Author: Joechin>, <Author: Sharon>]
In [25]: b1.authors.add(authors[2])
In [26]: b1.authors.add(authors[3])
In [27]: b1.authors.all()
Out[27]: [<Author: Joechin>, <Author: Sharon>, <Author: Lee>, <Author: Chinwe>]
In [28]: b1.authors.remove(joechin)
In [29]: b1.authors.all()
Out[29]: [<Author: Sharon>, <Author: Lee>, <Author: Chinwe>]
In [30]: b1.authors.remove(authors[3])
In [31]: b1.authors.all()
Out[31]: [<Author: Sharon>, <Author: Lee>]
In [32]: b1.authors.filter(name='Lee')
Out[32]: [<Author: Lee>]
In [33]: joechin
Out[33]: <Author: Joechin>
In [34]: joechin.book_set()
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-34-d6c12f13a5c4> in <module>()
----> 1 joechin.book_set()
D:\Python279\lib\site-packages\django\db\models\fields\related.pyc in __call__(s
elf, **kwargs)
884 # We use **kwargs rather than a kwarg argument to enforce th
e
885 # `manager='manager_name'` syntax.
--> 886 manager = getattr(self.model, kwargs.pop('manager'))
887 manager_class = create_many_related_manager(manager.__class_
_, rel)
888 return manager_class(
KeyError: u'manager'
In [35]: joechin.book_set
Out[35]: <django.db.models.fields.related.ManyRelatedManager at 0x37d9f70>
In [36]: joechin.book_set.all()
Out[36]: []
In [37]: joechin.book_set.a
joechin.book_set.add joechin.book_set.all
joechin.book_set.aggregate joechin.book_set.annotate
In [37]: joechin.book_set.add(b1)
In [38]: joechin.book_set.
joechin.book_set.add
joechin.book_set.aggregate
joechin.book_set.all
joechin.book_set.annotate
joechin.book_set.bulk_create
joechin.book_set.check
joechin.book_set.clear
joechin.book_set.complex_filter
joechin.book_set.contribute_to_class
joechin.book_set.core_filters
joechin.book_set.count
joechin.book_set.create
joechin.book_set.creation_counter
joechin.book_set.dates
joechin.book_set.datetimes
joechin.book_set.db
joechin.book_set.db_manager
joechin.book_set.deconstruct
joechin.book_set.defer
joechin.book_set.distinct
joechin.book_set.do_not_call_in_templates
joechin.book_set.earliest
joechin.book_set.exclude
joechin.book_set.exists
joechin.book_set.extra
joechin.book_set.filter
joechin.book_set.first
joechin.book_set.from_queryset
joechin.book_set.get
joechin.book_set.get_or_create
joechin.book_set.get_prefetch_queryset
joechin.book_set.get_queryset
joechin.book_set.in_bulk
joechin.book_set.instance
joechin.book_set.iterator
joechin.book_set.last
joechin.book_set.latest
joechin.book_set.model
joechin.book_set.name
joechin.book_set.none
joechin.book_set.only
joechin.book_set.order_by
joechin.book_set.prefetch_cache_name
joechin.book_set.prefetch_related
joechin.book_set.query_field_name
joechin.book_set.raw
joechin.book_set.related_val
joechin.book_set.remove
joechin.book_set.reverse
joechin.book_set.select_for_update
joechin.book_set.select_related
joechin.book_set.source_field
joechin.book_set.source_field_name
joechin.book_set.symmetrical
joechin.book_set.target_field
joechin.book_set.target_field_name
joechin.book_set.through
joechin.book_set.update
joechin.book_set.update_or_create
joechin.book_set.use_in_migrations
joechin.book_set.using
joechin.book_set.values
joechin.book_set.values_list
In [38]: joechin.book_set.create(name='python book2')
Out[38]: <Book: python book2>
In [39]: joechin.book_set.all()
Out[39]: [<Book: python book1>, <Book: python book2>]
In [40]: books = Book.objects.all()
In [41]: books
Out[41]: [<Book: python book1>, <Book: python book2>]
In [42]: joechin.book_set.a
joechin.book_set.add joechin.book_set.all
joechin.book_set.aggregate joechin.book_set.annotate
In [42]: joechin.book_set.all()
Out[42]: [<Book: python book1>, <Book: python book2>]
In [43]: joechin.book_set.remove(books[0])
In [44]: joechin.book_set.all()
Out[44]: [<Book: python book2>]
[05-02]
from blog.models import Author, Book
from django.shortcuts import render_to_response
def show_author(req):
authors = Author.objects.all()
return render_to_response('show_author.html', {'authors': authors})
def show_book(req):
books = Book.objects.all()
return render_to_response('show_book.html', {'books':books})
#Urls in urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
# Examples:
# url(r'^$', 'py1.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^blog/show_author/$', 'blog.views.show_author'),
url(r'^blog/show_book/$', 'blog.views.show_book'),
]
#show_author.html
{% for author in authors %}
<h3>{{author.name}}</h3>
<div>
{% for book in author.book_set.all %}
{{book}}
{% endfor %}
</div>
{% endfor %}
# show_book.html
{% for book in books %}
<div>
<h3>{{book.name}}</h3>
{% for author in book.authors.all %}
<li>{{author}}</li>
{%endfor%}
</div>
{% endfor %}
[05-03]
#comment csrf line in dictionary MIDDLEWARE_CLASSES in settings.py file.
from django import forms
from django.http import HttpResponse
from django.shortcuts import render_to_response
class UserForm(forms.Form):
name = forms.CharField()
# handle both get method and post method
def register(req):
if req.method == 'POST':
form = UserForm(req.POST)
if form.is_valid():
print form.cleaned_data
return HttpResponse('ok')
else:
form = UserForm()
return render_to_response('register.html', {'form': form})
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" class="">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Gebitang</title>
</head>
<body >
<form method = 'post'>
{{form}}
<input type="submit" value = "ok"/>
</form>
</body>
</html>
[05-03]
from django import forms
from django.http import HttpResponse
from django.shortcuts import render_to_response
class UserForm(forms.Form):
name = forms.CharField()
headImg = forms.FileField()
# handle both get method and post method
def register(req):
if req.method == 'POST':
form = UserForm(req.POST, req.FILES)
if form.is_valid():
#print form.cleaned_data['name']
print form.cleaned_data
#print req.FILES
print form.cleaned_data['headImg'].name
print form.cleaned_data['headImg'].size
fp = file('d:/Download/'+ form.cleaned_data['headImg'].name, 'wb')
s = form.cleaned_data['headImg'].read()
fp.write(s)
fp.close()
return HttpResponse('ok')
else:
form = UserForm()
return render_to_response('register.html', {'form': form})
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" class="">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Gebitang</title>
</head>
<body >
<div>User Register</div>
<div>
<form method='post' enctype='multipart/form-data'>
{{form.as_p}}
<input type="submit" value="ok" />
</form>
</div>
</body>
</html>
[05-04]
from django.db import models
class User(models.Model):
username = models.CharField(max_length=30)
headImg = models.FileField(upload_to='./upload/')
def __unicode__(self):
return self.username
from django.contrib import admin
from blog.models import User
admin.site.register(User)
[05-05]
'django.middleware.csrf.CsrfViewMiddleware',
;
from django.db import models
class User(models.Model):
username = models.CharField(max_length=30)
headImg = models.FileField(upload_to='./upload/')
def __unicode__(self):
return self.username
from django.shortcuts import render_to_response
from django import forms
from django.http import HttpResponse
from blog.models import User
class UserForm(forms.Form):
username = forms.CharField()
headImg = forms.FileField()
def register(req):
if req.method == "POST":
form = UserForm(req.POST, req.FILES)
if form.is_valid():
username = form.cleaned_data['username']
headImg = form.cleaned_data['headImg']
user = User()
user.username = username
user.headImg = headImg
user.save()
print username, headImg
return HttpResponse('OK')
else:
form = UserForm()
return render_to_response('register.html', {'form':form})
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" class="">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Gebitang</title>
</head>
<body >
<h1>Test</h1>
<form method="POSt" enctype="multipart/form-data">
{{form.as_p}}
<input type="submit" value="OK" />
</form>
</body>
</html>
[05-06]
#part content urls.py
urlpatterns = [
# Examples:
# url(r'^$', 'cookieprj.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^regist/$','blog.views.regist'),
url(r'^login/$','blog.views.login'),
url(r'^index/$','blog.views.index'),
url(r'^logout/$','blog.views.logout'),
]
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django import forms
from blog.models import User
class UserForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
def regist(req):
if req.method == "POST":
form = UserForm(req.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
User.objects.create(username=username, password=password)
return HttpResponseRedirect('/login/')
else:
form = UserForm()
return render_to_response('regist.html', {'form':form})
def login(req):
if req.method == "POST":
form = UserForm(req.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
users = User.objects.filter(username__exact=username, password__exact=password)
if users:
#should check how many
response = HttpResponseRedirect('/index/')
response.set_cookie('username',username, 3600)
return response
else:
return HttpResponseRedirect('/login/')
else:
form = UserForm()
return render_to_response('login.html', {'form':form})
def index(req):
username = req.COOKIES.get('username', '') #req.COOKIES['username']
#return HttpResponse('Welcome %s' % username)
return render_to_response('index.html', {'username':username})
def logout(req):
#del req
response = HttpResponse('logout')
response.delete_cookie('username')
return response
#regist.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" class="">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Gebitang</title>
</head>
<body >
<div>User Register</div>
<div>
<form method='post' >
{{form.as_p}}
<input type="submit" value="ok" />
</form>
</div>
</body>
</html>
#login.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" class="">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Gebitang</title>
</head>
<body >
<div>User Login</div>
<div>
<form method='post' >
{{form.as_p}}
<input type="submit" value="ok" />
</form>
</div>
</body>
</html>
#index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" class="">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Gebitang</title>
</head>
<body >
<h1>Welcome {{username}}</h1>
<a href='/logout/'>logout</a>
</body>
</html>
[05-07] offical session document
from django.shortcuts import render_to_response
from django import forms
from django.http import HttpResponse, HttpResponseRedirect
class UserForm(forms.Form):
username = forms.CharField()
def login(req):
if req.method == "POST":
form = UserForm(req.POST)
if form.is_valid():
username = form.cleaned_data['username']
req.session['username'] = username
return HttpResponseRedirect("/index/")
else:
form = UserForm()
return render_to_response('login.html', {'form':form})
def index(req):
username = req.session.get('username', 'default value')
#return HttpResponseRe('Welcome %s' %username)
return render_to_response('index.html', {'username':username})
def logout(req):
try:
username = req.session['username']
del req.session['username']
return HttpResponse('logout %s' %username)
except KeyError:
pass
return HttpResponse('logout without name')
[05-09] seems it's same as, or at least similar with class 10. Only apply for auth user.
F:\Dev\userproject>manage.py shell
F:\python279\lib\site-packages\django\db\backends\sqlite3\base.py:57: RuntimeWar
ning: SQLite received a naive datetime (2015-05-08 09:26:39.427000) while time z
one support is active.
RuntimeWarning)
Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)]
Type "copyright", "credits" or "license" for more information.
IPython 3.1.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: from django.contrib.auth.models import User
In [2]: User.objectss.all()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-2-151206ba0a42> in <module>()
----> 1 User.objectss.all()
AttributeError: type object 'User' has no attribute 'objectss'
In [3]: User.objects.all()
Out[3]: [<User: joechin>, <User: chin>]
In [4]: User.objects.create_user(username='Sharon', password='a', email='s@l.com
')
Out[4]: <User: Sharon>
In [5]: User.objects.all()
Out[5]: [<User: joechin>, <User: chin>, <User: Sharon>]
In [6]: s = User.objects.get(username__exact='sharon')
---------------------------------------------------------------------------
DoesNotExist Traceback (most recent call last)
<ipython-input-6-a0b4d675a154> in <module>()
----> 1 s = User.objects.get(username__exact='sharon')
F:\python279\lib\site-packages\django\db\models\manager.pyc in manager_method(se
lf, *args, **kwargs)
125 def create_method(name, method):
126 def manager_method(self, *args, **kwargs):
--> 127 return getattr(self.get_queryset(), name)(*args, **kwarg
s)
128 manager_method.__name__ = method.__name__
129 manager_method.__doc__ = method.__doc__
F:\python279\lib\site-packages\django\db\models\query.pyc in get(self, *args, **
kwargs)
332 raise self.model.DoesNotExist(
333 "%s matching query does not exist." %
--> 334 self.model._meta.object_name
335 )
336 raise self.model.MultipleObjectsReturned(
DoesNotExist: User matching query does not exist.
In [7]: s = User.objects.get(username__exact='joechin')
In [8]: s
Out[8]: <User: joechin>
In [9]: s.is_
s.is_active s.is_authenticated s.is_superuser
s.is_anonymous s.is_staff
In [9]: s.is_staff
Out[9]: True
In [10]: s = User.objects.get(username__exact='chin')
In [11]: s = User.objects.get(username__exact='sharon')
---------------------------------------------------------------------------
DoesNotExist Traceback (most recent call last)
<ipython-input-11-a0b4d675a154> in <module>()
----> 1 s = User.objects.get(username__exact='sharon')
F:\python279\lib\site-packages\django\db\models\manager.pyc in manager_method(se
lf, *args, **kwargs)
125 def create_method(name, method):
126 def manager_method(self, *args, **kwargs):
--> 127 return getattr(self.get_queryset(), name)(*args, **kwarg
s)
128 manager_method.__name__ = method.__name__
129 manager_method.__doc__ = method.__doc__
F:\python279\lib\site-packages\django\db\models\query.pyc in get(self, *args, **
kwargs)
332 raise self.model.DoesNotExist(
333 "%s matching query does not exist." %
--> 334 self.model._meta.object_name
335 )
336 raise self.model.MultipleObjectsReturned(
DoesNotExist: User matching query does not exist.
In [12]: s = User.objects.get(username__exact='Sharon')
In [13]: s.is
s.is_active s.is_authenticated s.is_superuser
s.is_anonymous s.is_staff
In [13]: s.is_staff
Out[13]: False
In [14]: s.is_staff = True
In [15]: s.first_name = 'sharon'
In [16]: s.last
s.last_login s.last_name
In [16]: s.last_name = 'lee'
In [17]: s
Out[17]: <User: Sharon>
In [18]: