@Gebitang
2015-05-08T01:42:31.000000Z
字数 29078
阅读 1909
django
my.ini under unzip location
[mysqld]basedir = D:\\dev\\mysql-5.6.24-winx64datadir = 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 prjnamedjango-admin startapp appnameurl(r'^blog/index', 'blog.views.index'),
from django.http import HttpResponsedef index(req):return HttpResponse('content')
python manager.py runserver
# Create your views here.'''from django.http import HttpResponsefrom django.template import loader, Contextdef index(req):t = loader.get_template('index.html')c = Context({})return HttpResponse(t.render({c}))'''from django.shortcuts import render_to_responsedef index(req):return render_to_response('index.html',{} )
#code in views.pyclass Person(object):def __init__(self, name, age, sex):self.name = nameself.age = ageself.sex = sex#mustn't have parametersdef say(self):love = ' LOVES'return self.name + love + ' Sharon.'from django.shortcuts import render_to_responsedef 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_responsedef 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, urlfrom django.contrib import adminfrom blog.views import indexurlpatterns = [# 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 foundfrom django.conf.urls.defaults import patterns, include, urlurlpatterns = patterns('blog.views',url(r'^blog/index/$', 'index'),)
[04-26]
# Create your views here.from django.template import loader, Context, Templatefrom django.http import HttpResponsedef index(req):t = loader.get_template('index.html')c = Context({'uname':'Sharon My Love'})return HttpResponse(t.render(c))# directly create templatedef index1(req):t = Template('<h1>hello {{uname}}</h1')c = Context({'uname':'Lee'})return HttpResponse(t.render(c))from django.shortcuts import render_to_responsedef 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 makemigrationsMigrations for 'blog':0001_initial.py:- Create model Employeemanage.py migrateOperations to perform:Synchronize unmigrated apps: staticfiles, messagesApply all migrations: admin, blog, contenttypes, auth, sessionsSynchronizing apps without migrations:Creating tables...Running deferred SQL...Installing custom SQL...Running migrations:Rendering model states... DONEApplying 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#1emp = Employee()emp.name = 'Joechin'emp.save()#2emp = Employee(name='Sharon')emp.save()#4emp = Employee.objects.create(name='Lee')##find allemps = Employee.objects.all()[<Employee: Employee object>, <Employee: Employee object>, <Employee: Employee 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 Employeefrom django.shortcuts import render_to_response#use databasedef 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 modelsclass Entry(models.Model):name = models.CharField(max_length=30)def __unicode__(self):return self.nameclass 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 modelssex_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 migrateadmin.py under app folder, content is:
from django.contrib import adminfrom blog.models import Useradmin.site.register(User)
manage.py runserver to surf you admin site:)[05-01]
from django.db import modelsclass Author(models.Model):name = models.CharField(max_length=30)def __unicode__(self):return self.nameclass Book(models.Model):name = models.CharField(max_length=30)authors = models.ManyToManyField(Author)def __unicode__(self):return self.name
manage.py makemigrations, manage.py migratemanage.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]: authorsOut[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(self, *args, **kwargs)125 def create_method(name, method):126 def manager_method(self, *args, **kwargs):--> 127 return getattr(self.get_queryset(), name)(*args, **kwargs)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)680681 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 clone699D:\Python279\lib\site-packages\django\db\models\sql\query.pyc in add_q(self, q_object)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_aliases)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(self, filter_expr, branch_negated, current_negated, can_reuse, connector, allow_joins)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 permittedin this query")D:\Python279\lib\site-packages\django\db\models\sql\query.pyc in solve_lookup_type(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(lookup_parts)]1032 if len(lookup_parts) == 0:D:\Python279\lib\site-packages\django\db\models\sql\query.pyc in names_to_path(self, names, opts, allow_many, fail_on_missing)1384 available = sorted(field_names + list(self.annotation_select))1385 raise FieldError("Cannot resolve keyword %r into field. "-> 1386 "Choices are: %s" % (name, ", ".join(available)))1387 break1388 # Check if we need any joins for concrete inheritance cases(theFieldError: Cannot resolve keyword 'name_exact' into field. Choices are: book, id, nameIn [14]: clear---------------------------------------------------------------------------NameError Traceback (most recent call last)<ipython-input-14-05cac50f47bd> in <module>()----> 1 clearNameError: name 'clear' is not definedIn [15]: clean---------------------------------------------------------------------------NameError Traceback (most recent call last)<ipython-input-15-175388b0347c> in <module>()----> 1 cleanNameError: name 'clean' is not definedIn [16]: alen = Author.objects.get(name='Joechin')In [17]: alenOut[17]: <Author: Joechin>In [18]: joechin = Author.objects.get(name='Joechin')In [19]: joechinOut[19]: <Author: Joechin>In [20]: b1.authors.add(joechin)In [21]: b1Out[21]: <Book: python book1>In [22]: b1.authors.add(authors[1])In [23]: b1.authors.allOut[23]: <bound method ManyRelatedManager.all of <django.db.models.fields.related.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]: joechinOut[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__(self, **kwargs)884 # We use **kwargs rather than a kwarg argument to enforce the885 # `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_setOut[35]: <django.db.models.fields.related.ManyRelatedManager at 0x37d9f70>In [36]: joechin.book_set.all()Out[36]: []In [37]: joechin.book_set.ajoechin.book_set.add joechin.book_set.alljoechin.book_set.aggregate joechin.book_set.annotateIn [37]: joechin.book_set.add(b1)In [38]: joechin.book_set.joechin.book_set.addjoechin.book_set.aggregatejoechin.book_set.alljoechin.book_set.annotatejoechin.book_set.bulk_createjoechin.book_set.checkjoechin.book_set.clearjoechin.book_set.complex_filterjoechin.book_set.contribute_to_classjoechin.book_set.core_filtersjoechin.book_set.countjoechin.book_set.createjoechin.book_set.creation_counterjoechin.book_set.datesjoechin.book_set.datetimesjoechin.book_set.dbjoechin.book_set.db_managerjoechin.book_set.deconstructjoechin.book_set.deferjoechin.book_set.distinctjoechin.book_set.do_not_call_in_templatesjoechin.book_set.earliestjoechin.book_set.excludejoechin.book_set.existsjoechin.book_set.extrajoechin.book_set.filterjoechin.book_set.firstjoechin.book_set.from_querysetjoechin.book_set.getjoechin.book_set.get_or_createjoechin.book_set.get_prefetch_querysetjoechin.book_set.get_querysetjoechin.book_set.in_bulkjoechin.book_set.instancejoechin.book_set.iteratorjoechin.book_set.lastjoechin.book_set.latestjoechin.book_set.modeljoechin.book_set.namejoechin.book_set.nonejoechin.book_set.onlyjoechin.book_set.order_byjoechin.book_set.prefetch_cache_namejoechin.book_set.prefetch_relatedjoechin.book_set.query_field_namejoechin.book_set.rawjoechin.book_set.related_valjoechin.book_set.removejoechin.book_set.reversejoechin.book_set.select_for_updatejoechin.book_set.select_relatedjoechin.book_set.source_fieldjoechin.book_set.source_field_namejoechin.book_set.symmetricaljoechin.book_set.target_fieldjoechin.book_set.target_field_namejoechin.book_set.throughjoechin.book_set.updatejoechin.book_set.update_or_createjoechin.book_set.use_in_migrationsjoechin.book_set.usingjoechin.book_set.valuesjoechin.book_set.values_listIn [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]: booksOut[41]: [<Book: python book1>, <Book: python book2>]In [42]: joechin.book_set.ajoechin.book_set.add joechin.book_set.alljoechin.book_set.aggregate joechin.book_set.annotateIn [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, Bookfrom django.shortcuts import render_to_responsedef 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.pyfrom django.conf.urls import include, urlfrom django.contrib import adminurlpatterns = [# 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 formsfrom django.http import HttpResponsefrom django.shortcuts import render_to_responseclass UserForm(forms.Form):name = forms.CharField()# handle both get method and post methoddef register(req):if req.method == 'POST':form = UserForm(req.POST)if form.is_valid():print form.cleaned_datareturn 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 formsfrom django.http import HttpResponsefrom django.shortcuts import render_to_responseclass UserForm(forms.Form):name = forms.CharField()headImg = forms.FileField()# handle both get method and post methoddef 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.FILESprint form.cleaned_data['headImg'].nameprint form.cleaned_data['headImg'].sizefp = 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 modelsclass 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 adminfrom blog.models import Useradmin.site.register(User)
[05-05]
'django.middleware.csrf.CsrfViewMiddleware',;
from django.db import modelsclass 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_responsefrom django import formsfrom django.http import HttpResponsefrom blog.models import Userclass 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 = usernameuser.headImg = headImguser.save()print username, headImgreturn 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.pyurlpatterns = [# 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_responsefrom django.http import HttpResponse, HttpResponseRedirectfrom django import formsfrom blog.models import Userclass 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 manyresponse = HttpResponseRedirect('/index/')response.set_cookie('username',username, 3600)return responseelse: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 reqresponse = 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_responsefrom django import formsfrom django.http import HttpResponse, HttpResponseRedirectclass 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'] = usernamereturn 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:passreturn 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 shellF:\python279\lib\site-packages\django\db\backends\sqlite3\base.py:57: RuntimeWarning: SQLite received a naive datetime (2015-05-08 09:26:39.427000) while time zone 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 UserIn [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(self, *args, **kwargs)125 def create_method(name, method):126 def manager_method(self, *args, **kwargs):--> 127 return getattr(self.get_queryset(), name)(*args, **kwargs)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_name335 )336 raise self.model.MultipleObjectsReturned(DoesNotExist: User matching query does not exist.In [7]: s = User.objects.get(username__exact='joechin')In [8]: sOut[8]: <User: joechin>In [9]: s.is_s.is_active s.is_authenticated s.is_superusers.is_anonymous s.is_staffIn [9]: s.is_staffOut[9]: TrueIn [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(self, *args, **kwargs)125 def create_method(name, method):126 def manager_method(self, *args, **kwargs):--> 127 return getattr(self.get_queryset(), name)(*args, **kwargs)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_name335 )336 raise self.model.MultipleObjectsReturned(DoesNotExist: User matching query does not exist.In [12]: s = User.objects.get(username__exact='Sharon')In [13]: s.iss.is_active s.is_authenticated s.is_superusers.is_anonymous s.is_staffIn [13]: s.is_staffOut[13]: FalseIn [14]: s.is_staff = TrueIn [15]: s.first_name = 'sharon'In [16]: s.lasts.last_login s.last_nameIn [16]: s.last_name = 'lee'In [17]: sOut[17]: <User: Sharon>In [18]: