[关闭]
@Gebitang 2015-05-08T01:42:31.000000Z 字数 29078 阅读 1682

Django

django


Installing MySQL on Microsoft Windows Using a noinstall Zip Archive

official doc

  1. [mysqld]
  2. basedir = D:\\dev\\mysql-5.6.24-winx64
  3. datadir = D:\\userDATA\\mysqldata


Django

Class 1: ABC

[04-22]
  1. django install.
    http://t.cn/RAlRXCE
    pip install Django check import django, print(django.get_version()
  2. create project. no suffix .py under windows environment.
    django-admin startproject prjname
  3. create app.
    django-admin startapp appname
  4. edit settings.py to add app with the created name
    app add --> appname
  5. edit config: urls.py, add line
    url(r'^blog/index', 'blog.views.index'),
  6. add method for this url.
  1. from django.http import HttpResponse
  2. def index(req):
  3. return HttpResponse('content')
  1. start dev server. Ctrl + C to stop server.
    python manager.py runserver
    visit:127.0.0.1:8000/blog/index

Class 2: how to use template

[04-23]
  1. Create folder templates under app 'blog'.
  2. Create template file, i.e. 'index.html'
  3. Modify the mothd for url. def index(req):
  1. # Create your views here.
  2. '''
  3. from django.http import HttpResponse
  4. from django.template import loader, Context
  5. def index(req):
  6. t = loader.get_template('index.html')
  7. c = Context({})
  8. return HttpResponse(t.render({c}))
  9. '''
  10. from django.shortcuts import render_to_response
  11. def index(req):
  12. return render_to_response('index.html',{} )
  1. Run Server to check

Class 3: dynamic render with parameter

[04-24]
  1. #code in views.py
  2. class Person(object):
  3. def __init__(self, name, age, sex):
  4. self.name = name
  5. self.age = age
  6. self.sex = sex
  7. #mustn't have parameters
  8. def say(self):
  9. love = ' LOVES'
  10. return self.name + love + ' Sharon.'
  11. from django.shortcuts import render_to_response
  12. def index(req):
  13. #user = {'name':'Joehcin', 'age':32, 'sex':'male'}
  14. user = Person('Joehcin', 32, 'Male')
  15. book_list = ['python', 'java', 'php', 'go']
  16. return render_to_response('index.html',{'title':'Gebitang page', 'user':user,'book_list':book_list} )
  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml" class="">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  6. <title>{{title}}</title>
  7. </head>
  8. <body >
  9. <h1>Hello {{user.name}}</h1>
  10. <li>age: {{user.age}}</li>
  11. <li>sex: {{user.sex}}</li>
  12. <li>{{book_list.0}}</li>
  13. <li>{{book_list.1}}</li>
  14. <li>{{book_list.2}}</li>
  15. <li>{{book_list.3}}</li>
  16. <p>
  17. <div>{{user.name}} say: {{user.say}}</div>
  18. </body>
  19. </html>

There is priority for them

Normal basic parameter
dictionary
object property
object method (the method mustn't have any parameter)
list


Class 4: if and for tags in template

[04-25]

  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml" class="">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  6. <title>{{title}}</title>
  7. </head>
  8. <body >
  9. {% if user %}
  10. <li>name: {{user.name}}</li>
  11. {% else %}
  12. 用户不存在
  13. {% endif %}
  14. {% for book in book_list %}
  15. <li>{{book}}</li>
  16. {% endfor %}
  17. {% for k, v in user.items %}
  18. <li>{{forloop.revcounter}}: {{k}}:{{v}}</li>
  19. {% endfor %}
  20. </body>
  21. </html>
  1. from django.shortcuts import render_to_response
  2. def index(req):
  3. user = {'name':'Joehcin', 'age':32, 'sex':'male'}
  4. # 'Person' object is not iterable
  5. #user = Person('Joehcin', 32, 'Male')
  6. book_list = ['python', 'java', 'C++', 'go']
  7. return render_to_response('index.html',{'title':'Gebitang page', 'user':user,'book_list':book_list} )

Class 5: URL configuration

[04-25]

  1. from django.conf.urls import include, url
  2. from django.contrib import admin
  3. from blog.views import index
  4. urlpatterns = [
  5. # Examples:
  6. # url(r'^$', 'gebitang.views.home', name='home'),
  7. # url(r'^blog/', include('blog.urls')),
  8. url(r'^admin/', include(admin.site.urls)),
  9. #url(r'^blog/index/\d{2}$',index),
  10. url(r'^blog/index/(\d{2})/$',index),
  11. #P must be upcase. P for parameters, can be empty
  12. # so (?P<id>\d{2}) will be like (\d{2}).
  13. # both need to define parameter in index method.
  14. # if the name is defined in url, the parameter name must be the same one in mehtod
  15. # if the name is empty in url, then anyone would work
  16. ]
  1. def index(req, parm):
  2. user = {'name':'Joehcin', 'age':69, 'sex':'male'}
  3. # 'Person' object is not iterable
  4. #user = Person('Joehcin', 32, 'Male')
  5. book_list = ['python', 'java', 'C++', 'go']
  6. 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

  1. # no module defaults found
  2. from django.conf.urls.defaults import patterns, include, url
  3. urlpatterns = patterns('blog.views',
  4. url(r'^blog/index/$', 'index'),
  5. )

Class 6: Three ways to use Template

[04-26]

  1. # Create your views here.
  2. from django.template import loader, Context, Template
  3. from django.http import HttpResponse
  4. def index(req):
  5. t = loader.get_template('index.html')
  6. c = Context({'uname':'Sharon My Love'})
  7. return HttpResponse(t.render(c))
  8. # directly create template
  9. def index1(req):
  10. t = Template('<h1>hello {{uname}}</h1')
  11. c = Context({'uname':'Lee'})
  12. return HttpResponse(t.render(c))
  13. from django.shortcuts import render_to_response
  14. def index2(req):
  15. return render_to_response('index.html', {'uname':'Lee'})

Class 7: Use mysql in Django

[04-27]

  1. INSTALLED_APPS = (
  2. 'django.contrib.admin',
  3. 'django.contrib.auth',
  4. 'django.contrib.contenttypes',
  5. 'django.contrib.sessions',
  6. 'django.contrib.messages',
  7. 'django.contrib.staticfiles',
  8. 'blog', #this is new created apps
  9. )

mysql -u root -p ; create database blog default charset=utf8;

  1. DATABASES = {
  2. 'default': {
  3. 'ENGINE': 'django.db.backends.mysql', #django.db.backends.mysql
  4. 'NAME': 'blog',
  5. 'USER':'root',
  6. 'PASSWORD':'123456',
  7. 'Host':'',
  8. 'PORT':'3306',
  9. }
  10. }
  1. from django.db import models
  2. # Create your models here.
  3. class Employee(models.Model):
  4. name = models.CharField(max_length=20)
  1. #Your models have changes that are not yet reflected in a migration, and so won't be applied.
  2. #Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.
  3. manage.py makemigrations
  4. Migrations for 'blog':
  5. 0001_initial.py:
  6. - Create model Employee
  7. manage.py migrate
  8. Operations to perform:
  9. Synchronize unmigrated apps: staticfiles, messages
  10. Apply all migrations: admin, blog, contenttypes, auth, sessions
  11. Synchronizing apps without migrations:
  12. Creating tables...
  13. Running deferred SQL...
  14. Installing custom SQL...
  15. Running migrations:
  16. Rendering model states... DONE
  17. Applying blog.0001_initial... OK

Class 8: Use Objects via database

[04-28]
- Three ways to create Object:

  1. from blog.models import Employee
  2. #1
  3. emp = Employee()
  4. emp.name = 'Joechin'
  5. emp.save()
  6. #2
  7. emp = Employee(name='Sharon')
  8. emp.save()
  9. #4
  10. emp = Employee.objects.create(name='Lee')
  11. ##find all
  12. emps = Employee.objects.all()
  13. [<Employee: Employee object>, <Employee: Employee object>, <Employee: E
  14. mployee object>, <Employee: Employee object>]
  1. from django.db import models
  2. # Create your models here.
  3. class Employee(models.Model):
  4. name = models.CharField(max_length=20)
  5. #this method will be called while find all objects. such as Employee.objecs.all()
  6. def __unicode__(self):
  7. return self.name
  1. from blog.models import Employee
  2. from django.shortcuts import render_to_response
  3. #use database
  4. def index(req):
  5. emps = Employee.objects.all()
  6. return render_to_response('index.html', {'emps':emps})
  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml" class="">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  6. <title>{{title}}</title>
  7. </head>
  8. <body >
  9. {{emps}}
  10. {%for emp in emps %}
  11. <div>{{forloop.counter}} {{emp}}</div>
  12. {% endfor %}
  13. <div>Total: {{emps|length}}</div>
  14. </body>
  15. </html>

[04-28] evening

  1. from django.db import models
  2. class Entry(models.Model):
  3. name = models.CharField(max_length=30)
  4. def __unicode__(self):
  5. return self.name
  6. class Blog(models.Model):
  7. name = models.CharField(max_length=30)
  8. entry = models.ForeignKey(Entry)
  9. def __unicode__(self):
  10. return self.name
  1. use blog;
  2. show tables; # blog_blog and blog_entry tables will be displayed.
  3. desc blog_blog;

Class 10: Django Admin

[04-30]
Official Docs
manage.py doc

  1. from django.db import models
  2. sex_choices = (
  3. ('f', 'famale'),
  4. ('m', 'male'),
  5. )
  6. class User(models.Model):
  7. name = models.CharField(max_length=30)
  8. sex = models.CharField(max_length=1, choices = sex_choices)
  9. def __unicode__(self):
  10. return self.name
  1. from django.contrib import admin
  2. from blog.models import User
  3. admin.site.register(User)

Class 11: database ManyToMany

[05-01]

  1. from django.db import models
  2. class Author(models.Model):
  3. name = models.CharField(max_length=30)
  4. def __unicode__(self):
  5. return self.name
  6. class Book(models.Model):
  7. name = models.CharField(max_length=30)
  8. authors = models.ManyToManyField(Author)
  9. def __unicode__(self):
  10. return self.name
  1. In [6]: Author.objects.create(name='Chinwe')
  2. Out[6]: <Author: Chinwe>
  3. In [7]: authors = Author.objects.all()
  4. In [8]: authors
  5. Out[8]: [<Author: Joechin>, <Author: Sharon>, <Author: Lee>, <Author: Chinwe>]
  6. In [9]: b1 = Book()
  7. In [10]: b1.name = 'python book1'
  8. In [11]: b1.save()
  9. In [12]: alen = Author.objecsts.get(name_exact='Joechin')
  10. ---------------------------------------------------------------------------
  11. AttributeError Traceback (most recent call last)
  12. <ipython-input-12-f742a45024c4> in <module>()
  13. ----> 1 alen = Author.objecsts.get(name_exact='Joechin')
  14. AttributeError: type object 'Author' has no attribute 'objecsts'
  15. In [13]: alen = Author.objects.get(name_exact='Joechin')
  16. ---------------------------------------------------------------------------
  17. FieldError Traceback (most recent call last)
  18. <ipython-input-13-d9e5576e1bca> in <module>()
  19. ----> 1 alen = Author.objects.get(name_exact='Joechin')
  20. D:\Python279\lib\site-packages\django\db\models\manager.pyc in manager_method(se
  21. lf, *args, **kwargs)
  22. 125 def create_method(name, method):
  23. 126 def manager_method(self, *args, **kwargs):
  24. --> 127 return getattr(self.get_queryset(), name)(*args, **kwarg
  25. s)
  26. 128 manager_method.__name__ = method.__name__
  27. 129 manager_method.__doc__ = method.__doc__
  28. D:\Python279\lib\site-packages\django\db\models\query.pyc in get(self, *args, **
  29. kwargs)
  30. 323 keyword arguments.
  31. 324 """
  32. --> 325 clone = self.filter(*args, **kwargs)
  33. 326 if self.query.can_filter():
  34. 327 clone = clone.order_by()
  35. D:\Python279\lib\site-packages\django\db\models\query.pyc in filter(self, *args,
  36. **kwargs)
  37. 677 set.
  38. 678 """
  39. --> 679 return self._filter_or_exclude(False, *args, **kwargs)
  40. 680
  41. 681 def exclude(self, *args, **kwargs):
  42. D:\Python279\lib\site-packages\django\db\models\query.pyc in _filter_or_exclude(
  43. self, negate, *args, **kwargs)
  44. 695 clone.query.add_q(~Q(*args, **kwargs))
  45. 696 else:
  46. --> 697 clone.query.add_q(Q(*args, **kwargs))
  47. 698 return clone
  48. 699
  49. D:\Python279\lib\site-packages\django\db\models\sql\query.pyc in add_q(self, q_o
  50. bject)
  51. 1299 existing_inner = set(
  52. 1300 (a for a in self.alias_map if self.alias_map[a].join_type ==
  53. INNER))
  54. -> 1301 clause, require_inner = self._add_q(where_part, self.used_aliase
  55. s)
  56. 1302 self.where.add(clause, AND)
  57. 1303 for hp in having_parts:
  58. D:\Python279\lib\site-packages\django\db\models\sql\query.pyc in _add_q(self, q_
  59. object, used_aliases, branch_negated, current_negated, allow_joins)
  60. 1326 child_clause, needed_inner = self.build_filter(
  61. 1327 child, can_reuse=used_aliases, branch_negated=branch
  62. _negated,
  63. -> 1328 current_negated=current_negated, connector=connector
  64. , allow_joins=allow_joins)
  65. 1329 joinpromoter.add_votes(needed_inner)
  66. 1330 target_clause.add(child_clause, connector)
  67. D:\Python279\lib\site-packages\django\db\models\sql\query.pyc in build_filter(se
  68. lf, filter_expr, branch_negated, current_negated, can_reuse, connector, allow_jo
  69. ins)
  70. 1142 if not arg:
  71. 1143 raise FieldError("Cannot parse keyword query %r" % arg)
  72. -> 1144 lookups, parts, reffed_aggregate = self.solve_lookup_type(arg)
  73. 1145 if not allow_joins and len(parts) > 1:
  74. 1146 raise FieldError("Joined field references are not permitted
  75. in this query")
  76. D:\Python279\lib\site-packages\django\db\models\sql\query.pyc in solve_lookup_ty
  77. pe(self, lookup)
  78. 1028 if aggregate:
  79. 1029 return aggregate_lookups, (), aggregate
  80. -> 1030 _, field, _, lookup_parts = self.names_to_path(lookup_splitted,
  81. self.get_meta())
  82. 1031 field_parts = lookup_splitted[0:len(lookup_splitted) - len(looku
  83. p_parts)]
  84. 1032 if len(lookup_parts) == 0:
  85. D:\Python279\lib\site-packages\django\db\models\sql\query.pyc in names_to_path(s
  86. elf, names, opts, allow_many, fail_on_missing)
  87. 1384 available = sorted(field_names + list(self.annotatio
  88. n_select))
  89. 1385 raise FieldError("Cannot resolve keyword %r into fie
  90. ld. "
  91. -> 1386 "Choices are: %s" % (name, ", ".joi
  92. n(available)))
  93. 1387 break
  94. 1388 # Check if we need any joins for concrete inheritance cases
  95. (the
  96. FieldError: Cannot resolve keyword 'name_exact' into field. Choices are: book, i
  97. d, name
  98. In [14]: clear
  99. ---------------------------------------------------------------------------
  100. NameError Traceback (most recent call last)
  101. <ipython-input-14-05cac50f47bd> in <module>()
  102. ----> 1 clear
  103. NameError: name 'clear' is not defined
  104. In [15]: clean
  105. ---------------------------------------------------------------------------
  106. NameError Traceback (most recent call last)
  107. <ipython-input-15-175388b0347c> in <module>()
  108. ----> 1 clean
  109. NameError: name 'clean' is not defined
  110. In [16]: alen = Author.objects.get(name='Joechin')
  111. In [17]: alen
  112. Out[17]: <Author: Joechin>
  113. In [18]: joechin = Author.objects.get(name='Joechin')
  114. In [19]: joechin
  115. Out[19]: <Author: Joechin>
  116. In [20]: b1.authors.add(joechin)
  117. In [21]: b1
  118. Out[21]: <Book: python book1>
  119. In [22]: b1.authors.add(authors[1])
  120. In [23]: b1.authors.all
  121. Out[23]: <bound method ManyRelatedManager.all of <django.db.models.fields.relate
  122. d.ManyRelatedManager object at 0x037A89F0>>
  123. In [24]: b1.authors.all()
  124. Out[24]: [<Author: Joechin>, <Author: Sharon>]
  125. In [25]: b1.authors.add(authors[2])
  126. In [26]: b1.authors.add(authors[3])
  127. In [27]: b1.authors.all()
  128. Out[27]: [<Author: Joechin>, <Author: Sharon>, <Author: Lee>, <Author: Chinwe>]
  129. In [28]: b1.authors.remove(joechin)
  130. In [29]: b1.authors.all()
  131. Out[29]: [<Author: Sharon>, <Author: Lee>, <Author: Chinwe>]
  132. In [30]: b1.authors.remove(authors[3])
  133. In [31]: b1.authors.all()
  134. Out[31]: [<Author: Sharon>, <Author: Lee>]
  135. In [32]: b1.authors.filter(name='Lee')
  136. Out[32]: [<Author: Lee>]
  137. In [33]: joechin
  138. Out[33]: <Author: Joechin>
  139. In [34]: joechin.book_set()
  140. ---------------------------------------------------------------------------
  141. KeyError Traceback (most recent call last)
  142. <ipython-input-34-d6c12f13a5c4> in <module>()
  143. ----> 1 joechin.book_set()
  144. D:\Python279\lib\site-packages\django\db\models\fields\related.pyc in __call__(s
  145. elf, **kwargs)
  146. 884 # We use **kwargs rather than a kwarg argument to enforce th
  147. e
  148. 885 # `manager='manager_name'` syntax.
  149. --> 886 manager = getattr(self.model, kwargs.pop('manager'))
  150. 887 manager_class = create_many_related_manager(manager.__class_
  151. _, rel)
  152. 888 return manager_class(
  153. KeyError: u'manager'
  154. In [35]: joechin.book_set
  155. Out[35]: <django.db.models.fields.related.ManyRelatedManager at 0x37d9f70>
  156. In [36]: joechin.book_set.all()
  157. Out[36]: []
  158. In [37]: joechin.book_set.a
  159. joechin.book_set.add joechin.book_set.all
  160. joechin.book_set.aggregate joechin.book_set.annotate
  161. In [37]: joechin.book_set.add(b1)
  162. In [38]: joechin.book_set.
  163. joechin.book_set.add
  164. joechin.book_set.aggregate
  165. joechin.book_set.all
  166. joechin.book_set.annotate
  167. joechin.book_set.bulk_create
  168. joechin.book_set.check
  169. joechin.book_set.clear
  170. joechin.book_set.complex_filter
  171. joechin.book_set.contribute_to_class
  172. joechin.book_set.core_filters
  173. joechin.book_set.count
  174. joechin.book_set.create
  175. joechin.book_set.creation_counter
  176. joechin.book_set.dates
  177. joechin.book_set.datetimes
  178. joechin.book_set.db
  179. joechin.book_set.db_manager
  180. joechin.book_set.deconstruct
  181. joechin.book_set.defer
  182. joechin.book_set.distinct
  183. joechin.book_set.do_not_call_in_templates
  184. joechin.book_set.earliest
  185. joechin.book_set.exclude
  186. joechin.book_set.exists
  187. joechin.book_set.extra
  188. joechin.book_set.filter
  189. joechin.book_set.first
  190. joechin.book_set.from_queryset
  191. joechin.book_set.get
  192. joechin.book_set.get_or_create
  193. joechin.book_set.get_prefetch_queryset
  194. joechin.book_set.get_queryset
  195. joechin.book_set.in_bulk
  196. joechin.book_set.instance
  197. joechin.book_set.iterator
  198. joechin.book_set.last
  199. joechin.book_set.latest
  200. joechin.book_set.model
  201. joechin.book_set.name
  202. joechin.book_set.none
  203. joechin.book_set.only
  204. joechin.book_set.order_by
  205. joechin.book_set.prefetch_cache_name
  206. joechin.book_set.prefetch_related
  207. joechin.book_set.query_field_name
  208. joechin.book_set.raw
  209. joechin.book_set.related_val
  210. joechin.book_set.remove
  211. joechin.book_set.reverse
  212. joechin.book_set.select_for_update
  213. joechin.book_set.select_related
  214. joechin.book_set.source_field
  215. joechin.book_set.source_field_name
  216. joechin.book_set.symmetrical
  217. joechin.book_set.target_field
  218. joechin.book_set.target_field_name
  219. joechin.book_set.through
  220. joechin.book_set.update
  221. joechin.book_set.update_or_create
  222. joechin.book_set.use_in_migrations
  223. joechin.book_set.using
  224. joechin.book_set.values
  225. joechin.book_set.values_list
  226. In [38]: joechin.book_set.create(name='python book2')
  227. Out[38]: <Book: python book2>
  228. In [39]: joechin.book_set.all()
  229. Out[39]: [<Book: python book1>, <Book: python book2>]
  230. In [40]: books = Book.objects.all()
  231. In [41]: books
  232. Out[41]: [<Book: python book1>, <Book: python book2>]
  233. In [42]: joechin.book_set.a
  234. joechin.book_set.add joechin.book_set.all
  235. joechin.book_set.aggregate joechin.book_set.annotate
  236. In [42]: joechin.book_set.all()
  237. Out[42]: [<Book: python book1>, <Book: python book2>]
  238. In [43]: joechin.book_set.remove(books[0])
  239. In [44]: joechin.book_set.all()
  240. Out[44]: [<Book: python book2>]

Class 12: Show data in templates

[05-02]

  1. from blog.models import Author, Book
  2. from django.shortcuts import render_to_response
  3. def show_author(req):
  4. authors = Author.objects.all()
  5. return render_to_response('show_author.html', {'authors': authors})
  6. def show_book(req):
  7. books = Book.objects.all()
  8. return render_to_response('show_book.html', {'books':books})
  9. #Urls in urls.py
  10. from django.conf.urls import include, url
  11. from django.contrib import admin
  12. urlpatterns = [
  13. # Examples:
  14. # url(r'^$', 'py1.views.home', name='home'),
  15. # url(r'^blog/', include('blog.urls')),
  16. url(r'^admin/', include(admin.site.urls)),
  17. url(r'^blog/show_author/$', 'blog.views.show_author'),
  18. url(r'^blog/show_book/$', 'blog.views.show_book'),
  19. ]
  1. #show_author.html
  2. {% for author in authors %}
  3. <h3>{{author.name}}</h3>
  4. <div>
  5. {% for book in author.book_set.all %}
  6. {{book}}
  7. {% endfor %}
  8. </div>
  9. {% endfor %}
  10. # show_book.html
  11. {% for book in books %}
  12. <div>
  13. <h3>{{book.name}}</h3>
  14. {% for author in book.authors.all %}
  15. <li>{{author}}</li>
  16. {%endfor%}
  17. </div>
  18. {% endfor %}

Class 13: Basic form

[05-03]

  1. #comment csrf line in dictionary MIDDLEWARE_CLASSES in settings.py file.
  2. from django import forms
  3. from django.http import HttpResponse
  4. from django.shortcuts import render_to_response
  5. class UserForm(forms.Form):
  6. name = forms.CharField()
  7. # handle both get method and post method
  8. def register(req):
  9. if req.method == 'POST':
  10. form = UserForm(req.POST)
  11. if form.is_valid():
  12. print form.cleaned_data
  13. return HttpResponse('ok')
  14. else:
  15. form = UserForm()
  16. return render_to_response('register.html', {'form': form})
  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml" class="">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  6. <title>Gebitang</title>
  7. </head>
  8. <body >
  9. <form method = 'post'>
  10. {{form}}
  11. <input type="submit" value = "ok"/>
  12. </form>
  13. </body>
  14. </html>

Class 14: Basic form File operation

[05-03]

  1. from django import forms
  2. from django.http import HttpResponse
  3. from django.shortcuts import render_to_response
  4. class UserForm(forms.Form):
  5. name = forms.CharField()
  6. headImg = forms.FileField()
  7. # handle both get method and post method
  8. def register(req):
  9. if req.method == 'POST':
  10. form = UserForm(req.POST, req.FILES)
  11. if form.is_valid():
  12. #print form.cleaned_data['name']
  13. print form.cleaned_data
  14. #print req.FILES
  15. print form.cleaned_data['headImg'].name
  16. print form.cleaned_data['headImg'].size
  17. fp = file('d:/Download/'+ form.cleaned_data['headImg'].name, 'wb')
  18. s = form.cleaned_data['headImg'].read()
  19. fp.write(s)
  20. fp.close()
  21. return HttpResponse('ok')
  22. else:
  23. form = UserForm()
  24. return render_to_response('register.html', {'form': form})
  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml" class="">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  6. <title>Gebitang</title>
  7. </head>
  8. <body >
  9. <div>User Register</div>
  10. <div>
  11. <form method='post' enctype='multipart/form-data'>
  12. {{form.as_p}}
  13. <input type="submit" value="ok" />
  14. </form>
  15. </div>
  16. </body>
  17. </html>

Class 15: Upload file Via Admin to DB

[05-04]

  1. from django.db import models
  2. class User(models.Model):
  3. username = models.CharField(max_length=30)
  4. headImg = models.FileField(upload_to='./upload/')
  5. def __unicode__(self):
  6. return self.username
  1. from django.contrib import admin
  2. from blog.models import User
  3. admin.site.register(User)

Class 16: Upload file via Form & DB

[05-05]

  1. from django.db import models
  2. class User(models.Model):
  3. username = models.CharField(max_length=30)
  4. headImg = models.FileField(upload_to='./upload/')
  5. def __unicode__(self):
  6. return self.username
  1. from django.shortcuts import render_to_response
  2. from django import forms
  3. from django.http import HttpResponse
  4. from blog.models import User
  5. class UserForm(forms.Form):
  6. username = forms.CharField()
  7. headImg = forms.FileField()
  8. def register(req):
  9. if req.method == "POST":
  10. form = UserForm(req.POST, req.FILES)
  11. if form.is_valid():
  12. username = form.cleaned_data['username']
  13. headImg = form.cleaned_data['headImg']
  14. user = User()
  15. user.username = username
  16. user.headImg = headImg
  17. user.save()
  18. print username, headImg
  19. return HttpResponse('OK')
  20. else:
  21. form = UserForm()
  22. return render_to_response('register.html', {'form':form})
  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml" class="">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  6. <title>Gebitang</title>
  7. </head>
  8. <body >
  9. <h1>Test</h1>
  10. <form method="POSt" enctype="multipart/form-data">
  11. {{form.as_p}}
  12. <input type="submit" value="OK" />
  13. </form>
  14. </body>
  15. </html>

[05-06]

  1. #part content urls.py
  2. urlpatterns = [
  3. # Examples:
  4. # url(r'^$', 'cookieprj.views.home', name='home'),
  5. # url(r'^blog/', include('blog.urls')),
  6. url(r'^admin/', include(admin.site.urls)),
  7. url(r'^regist/$','blog.views.regist'),
  8. url(r'^login/$','blog.views.login'),
  9. url(r'^index/$','blog.views.index'),
  10. url(r'^logout/$','blog.views.logout'),
  11. ]
  1. from django.shortcuts import render_to_response
  2. from django.http import HttpResponse, HttpResponseRedirect
  3. from django import forms
  4. from blog.models import User
  5. class UserForm(forms.Form):
  6. username = forms.CharField()
  7. password = forms.CharField(widget=forms.PasswordInput)
  8. def regist(req):
  9. if req.method == "POST":
  10. form = UserForm(req.POST)
  11. if form.is_valid():
  12. username = form.cleaned_data['username']
  13. password = form.cleaned_data['password']
  14. User.objects.create(username=username, password=password)
  15. return HttpResponseRedirect('/login/')
  16. else:
  17. form = UserForm()
  18. return render_to_response('regist.html', {'form':form})
  19. def login(req):
  20. if req.method == "POST":
  21. form = UserForm(req.POST)
  22. if form.is_valid():
  23. username = form.cleaned_data['username']
  24. password = form.cleaned_data['password']
  25. users = User.objects.filter(username__exact=username, password__exact=password)
  26. if users:
  27. #should check how many
  28. response = HttpResponseRedirect('/index/')
  29. response.set_cookie('username',username, 3600)
  30. return response
  31. else:
  32. return HttpResponseRedirect('/login/')
  33. else:
  34. form = UserForm()
  35. return render_to_response('login.html', {'form':form})
  36. def index(req):
  37. username = req.COOKIES.get('username', '') #req.COOKIES['username']
  38. #return HttpResponse('Welcome %s' % username)
  39. return render_to_response('index.html', {'username':username})
  40. def logout(req):
  41. #del req
  42. response = HttpResponse('logout')
  43. response.delete_cookie('username')
  44. return response
  1. #regist.html
  2. <!DOCTYPE html>
  3. <html xmlns="http://www.w3.org/1999/xhtml" class="">
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  6. <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  7. <title>Gebitang</title>
  8. </head>
  9. <body >
  10. <div>User Register</div>
  11. <div>
  12. <form method='post' >
  13. {{form.as_p}}
  14. <input type="submit" value="ok" />
  15. </form>
  16. </div>
  17. </body>
  18. </html>
  19. #login.html
  20. <!DOCTYPE html>
  21. <html xmlns="http://www.w3.org/1999/xhtml" class="">
  22. <head>
  23. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  24. <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  25. <title>Gebitang</title>
  26. </head>
  27. <body >
  28. <div>User Login</div>
  29. <div>
  30. <form method='post' >
  31. {{form.as_p}}
  32. <input type="submit" value="ok" />
  33. </form>
  34. </div>
  35. </body>
  36. </html>
  37. #index.html
  38. <!DOCTYPE html>
  39. <html xmlns="http://www.w3.org/1999/xhtml" class="">
  40. <head>
  41. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  42. <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  43. <title>Gebitang</title>
  44. </head>
  45. <body >
  46. <h1>Welcome {{username}}</h1>
  47. <a href='/logout/'>logout</a>
  48. </body>
  49. </html>

Class 18: Use sessions

[05-07] offical session document

  1. from django.shortcuts import render_to_response
  2. from django import forms
  3. from django.http import HttpResponse, HttpResponseRedirect
  4. class UserForm(forms.Form):
  5. username = forms.CharField()
  6. def login(req):
  7. if req.method == "POST":
  8. form = UserForm(req.POST)
  9. if form.is_valid():
  10. username = form.cleaned_data['username']
  11. req.session['username'] = username
  12. return HttpResponseRedirect("/index/")
  13. else:
  14. form = UserForm()
  15. return render_to_response('login.html', {'form':form})
  16. def index(req):
  17. username = req.session.get('username', 'default value')
  18. #return HttpResponseRe('Welcome %s' %username)
  19. return render_to_response('index.html', {'username':username})
  20. def logout(req):
  21. try:
  22. username = req.session['username']
  23. del req.session['username']
  24. return HttpResponse('logout %s' %username)
  25. except KeyError:
  26. pass
  27. return HttpResponse('logout without name')

Class 19: User Auth

[05-09] seems it's same as, or at least similar with class 10. Only apply for auth user.

  1. F:\Dev\userproject>manage.py shell
  2. F:\python279\lib\site-packages\django\db\backends\sqlite3\base.py:57: RuntimeWar
  3. ning: SQLite received a naive datetime (2015-05-08 09:26:39.427000) while time z
  4. one support is active.
  5. RuntimeWarning)
  6. Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)]
  7. Type "copyright", "credits" or "license" for more information.
  8. IPython 3.1.0 -- An enhanced Interactive Python.
  9. ? -> Introduction and overview of IPython's features.
  10. %quickref -> Quick reference.
  11. help -> Python's own help system.
  12. object? -> Details about 'object', use 'object??' for extra details.
  13. In [1]: from django.contrib.auth.models import User
  14. In [2]: User.objectss.all()
  15. ---------------------------------------------------------------------------
  16. AttributeError Traceback (most recent call last)
  17. <ipython-input-2-151206ba0a42> in <module>()
  18. ----> 1 User.objectss.all()
  19. AttributeError: type object 'User' has no attribute 'objectss'
  20. In [3]: User.objects.all()
  21. Out[3]: [<User: joechin>, <User: chin>]
  22. In [4]: User.objects.create_user(username='Sharon', password='a', email='s@l.com
  23. ')
  24. Out[4]: <User: Sharon>
  25. In [5]: User.objects.all()
  26. Out[5]: [<User: joechin>, <User: chin>, <User: Sharon>]
  27. In [6]: s = User.objects.get(username__exact='sharon')
  28. ---------------------------------------------------------------------------
  29. DoesNotExist Traceback (most recent call last)
  30. <ipython-input-6-a0b4d675a154> in <module>()
  31. ----> 1 s = User.objects.get(username__exact='sharon')
  32. F:\python279\lib\site-packages\django\db\models\manager.pyc in manager_method(se
  33. lf, *args, **kwargs)
  34. 125 def create_method(name, method):
  35. 126 def manager_method(self, *args, **kwargs):
  36. --> 127 return getattr(self.get_queryset(), name)(*args, **kwarg
  37. s)
  38. 128 manager_method.__name__ = method.__name__
  39. 129 manager_method.__doc__ = method.__doc__
  40. F:\python279\lib\site-packages\django\db\models\query.pyc in get(self, *args, **
  41. kwargs)
  42. 332 raise self.model.DoesNotExist(
  43. 333 "%s matching query does not exist." %
  44. --> 334 self.model._meta.object_name
  45. 335 )
  46. 336 raise self.model.MultipleObjectsReturned(
  47. DoesNotExist: User matching query does not exist.
  48. In [7]: s = User.objects.get(username__exact='joechin')
  49. In [8]: s
  50. Out[8]: <User: joechin>
  51. In [9]: s.is_
  52. s.is_active s.is_authenticated s.is_superuser
  53. s.is_anonymous s.is_staff
  54. In [9]: s.is_staff
  55. Out[9]: True
  56. In [10]: s = User.objects.get(username__exact='chin')
  57. In [11]: s = User.objects.get(username__exact='sharon')
  58. ---------------------------------------------------------------------------
  59. DoesNotExist Traceback (most recent call last)
  60. <ipython-input-11-a0b4d675a154> in <module>()
  61. ----> 1 s = User.objects.get(username__exact='sharon')
  62. F:\python279\lib\site-packages\django\db\models\manager.pyc in manager_method(se
  63. lf, *args, **kwargs)
  64. 125 def create_method(name, method):
  65. 126 def manager_method(self, *args, **kwargs):
  66. --> 127 return getattr(self.get_queryset(), name)(*args, **kwarg
  67. s)
  68. 128 manager_method.__name__ = method.__name__
  69. 129 manager_method.__doc__ = method.__doc__
  70. F:\python279\lib\site-packages\django\db\models\query.pyc in get(self, *args, **
  71. kwargs)
  72. 332 raise self.model.DoesNotExist(
  73. 333 "%s matching query does not exist." %
  74. --> 334 self.model._meta.object_name
  75. 335 )
  76. 336 raise self.model.MultipleObjectsReturned(
  77. DoesNotExist: User matching query does not exist.
  78. In [12]: s = User.objects.get(username__exact='Sharon')
  79. In [13]: s.is
  80. s.is_active s.is_authenticated s.is_superuser
  81. s.is_anonymous s.is_staff
  82. In [13]: s.is_staff
  83. Out[13]: False
  84. In [14]: s.is_staff = True
  85. In [15]: s.first_name = 'sharon'
  86. In [16]: s.last
  87. s.last_login s.last_name
  88. In [16]: s.last_name = 'lee'
  89. In [17]: s
  90. Out[17]: <User: Sharon>
  91. In [18]:
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注