Advertisement
johnmahugu

python - full django cheatsheet

Jul 23rd, 2015
318
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 24.31 KB | None | 0 0
  1. = Template Tags Cheat Sheet =
  2.  
  3. == Inheritance and Inclusion ==
  4.  
  5.  * {% extends "base.html "%}
  6.  * {% block content %} ... {% endblock %} or {% block content %} ... {% endblock content %}
  7.  * {% include "foo/bar.html" %}
  8.  * {% ssi /home/html/ljworld.com/includes/right_generic.html %}
  9.  
  10. == Filters and Tags ==
  11.  
  12.  * {% load <tag_or_filter_lib> %}
  13.  * {% filter <filter>[|<filter>...] %}
  14.  
  15. == Control ==
  16.  
  17.  * {% for o in some_list %} ... {% endfor %}
  18.  * {% ifchanged %} (Content to check status of) {% endifchanged %}
  19.  * {% if <var> %} ... {% endif %}
  20.  * {% if[not]equal user.id comment.user_id %} ... [{% else %}] ... {% endif[not]equal %}
  21.  * {% cycle row1,row2 %}
  22.  * {% cycle row1,row2 as rowcolors %}
  23.  ** {% cycle rowcolors %}
  24.  * {% firstof var1 var2 var3 %}
  25.  * {% regroup people by gender as grouped %} ... {% for group in grouped %} {{ group.grouper }} ...
  26.  
  27. == Others ==
  28.  
  29.  * {% templatetag  (openblock|closeblock|openvariable|closevariable|openbrace|closebrace) %}
  30.  * {% widthratio this_value max_value 100 %}
  31.  * It is {% now "jS F Y H:i" %}
  32.  * {% spaceless %} ... {% endspaceless %}
  33. django_db_cheat.txtPage 1 of 2 Aug/2008
  34. 1#Model of question:2
  35. class
  36.  Blog(models.Model): 3 name=models.CharField(max_length=100) 4 tagline=models.TextField() 5 bestEntry=ForeignKey("mutually_referential.Entry")  6# two way relations usually illegal unless specified as referential7# myId = models.AutoField(primary_key=True)8# by default the primary key is called 'id' - but overridable9# 'blog.pk' to will refer to the primary key regardless of what its called1011
  37. class
  38.  Author(models.Model): 12 name=models.CharField(max_length=50) 13 email=models.EmailField() 1415
  39. class
  40.  Entry(models.Model): 16 blog=models.ForeignKey(Blog)  17# automagically in any Blog instance b, there is now a set called b.entry_set18# blog = models.ForeignKey(Blog, related_name='custom_name')19# (this overrides default name of blog.entry_set with blog.custom_name)20 headline=models.CharField(max_length=255) 21 body_text=models.TextField() 22 pub_date=models.DateTimeField() 23 authors=models.ManyToManyField(Author) 24
  41. class
  42.  Meta:25 ordering= ('-pub_date', 'headline') 26
  43. def
  44.  articles_from_same_day(self): 27
  45. return
  46. Entry.objects.filter(pub_date=self.pub_date).exclude(id=self.id) 28# a.articles_from_same_day() returns a resultset2930
  47. class
  48.  EntryDetail(models.Model): 31 entry=models.OneToOneField(Entry) 32 details=models.TextField() 3334#Inserting35 b=Blog(name='Beatles Blog',tagline='All the latest Beatles news.') 36 b.save() 37 bb=Blog(id=3,name='Not Cheddar',tagline='Anything but cheese.') 38 bb.save() # Overrides the previous blog with ID=3! 3940#Manager41 Entry.objects.get(id=2) # gets id=2 42 e=Entry.objects.select_related().get(id=2) 43
  49. print
  50. e.blog# Doesn't hit the database twice; uses cached version. 4445#Filter and Exclusion - it is a lazy operation, not done until iterated/read46 Entry.objects.filter(pub_date__year=2006) 47 Entry.objects.filter( 48 headline__startswith='What').exclude( 49 pub_date__gte=datetime.now()).filter( 50 pub_date__gte=datetime(2005, 1, 1))  51 Entry.objects.filter(blog=b) # Query using object instance 52 Entry.objects.filter(blog=b.id) # Query using id from instance 53 Entry.objects.filter(blog=5) # Query using id directly 5455#Sorting56 Entry.objects.order_by('pub_date', '-headline') 5758# Deleting59 e.delete() #If there are dependencies, they will be deleted too 60 Entry.objects.filter(pub_date__year=2005).delete() 61# warning - when deleting a resultset, you might delete many entries6263# Updating64 e.headline= 'Everything is the same' 65 e.save()
  51. - 1 -
  52. django_db_cheat.txtPage 2 of 2 Aug/2008
  53. 66 Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same')  67 Entry.objects.all().update(blog=b) 68# need to save if you use bulk69
  54. for
  55. item
  56. in
  57. Entry.objects.all(): 70 item.save() 7172# Many-to-One - via ForeignKey73 b=Blog.objects.get(id=1) 74 b.entry_set.all() # Returns all Entry objects related to Blog. 75 b.entry_set.filter(headline__contains='Lennon') 76 b.entry_set.count() 77 e=Entry.objects.get(id=234) 78 b.entry_set.add(e) # Associates Entry e with Blog b. 79 e=b.entry_set.create(headline='Hello',body_text='Hi',pub_date=datetime.date(2005, 1, 1)) 80 b.entry_set.remove(e) # Disassociates Entry e from Blog b. 81 b.entry_set.clear() 82 b.entry_set= [e1,e2] # You can't set to one element need [e1,] 8384# One-to-One - via OneToOneField85 ed=EntryDetail.objects.get(id=2) 86 ed.entry# Returns the related Entry object. 87 e=Entry.objects.get(id=2) 88 e.entrydetail89 e.entrydetail=ed 9091# Many-to-Many - via ManyToManyField92 e=Entry.objects.get(id=3) 93 e.authors.all() # R
  58.  
  59. eturns all Author objects for this Entry.94 e.authors.filter(name__contains='John') 95 a=Author.objects.get(id=5) 96 a.entry_set.all() # Returns all Entry objects for this Author. 97 a.entry_set.filter(body_text__contains='John') 98 a.entry_set.create(....) #just like normal create 99100# Misc functions101 Author.objects.get_or_create(name='David',defaults={'email': 'generic@email.com'}) 102103# Returning a url to go to object:104# suppose your urlconf had105# (r'/archive/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/$', archive_view)106
  60. from
  61. django.db.models
  62. import
  63. permalink107
  64. def
  65.  get_absolute_url(self): 108
  66. return
  67.  ('archive_view', (), { 109'year':self.created.year, 110'month':self.created.month, 111'day':self.created.day}) 112
  68. get_absolute_url=permalink(get_absolute_url) 113114# Doing custom sql:115
  69. def
  70.  my_custom_sql(self): 116
  71. from
  72. django.db
  73. import
  74. connection117 cursor=connection.cursor() 118 cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz]) 119 row=cursor.fetchone() 120
  75. return
  76. row121122# Field Type Reference123 AutoField,BooleanField,CharField,CommaSeparatedIntegerField,DateField,DateTimeField,  124 DecimalField,EmailField,FileField,FilePathField,FloatField,ImageField,IntegerField,  125 IPAddressField,NullBooleanField,PhoneNumberField,PositiveIntegerField,  126 PositiveSmallIntegerField,SlugField,SmallIntegerField,TextField,TimeField,URLField,  127 USStateField,XMLField128129# Model Methods130 __unicode__,get_absolute_url
  77. - 2 -
  78. Quick and simple urlpatterns code examples for django cheatsheet
  79. See more
  80.  
  81. django_url_cheat.txtPage 1 of 2 Aug/2008
  82. 1
  83. from
  84. django.conf.urls.defaults
  85. import
  86.  *2 urlpatterns=patterns('', 3# (regular exp, function, optional dictionary, optional name)4# Doesn’t differentiate request method, all go to the same function5(r'^articles/2003/$', 'news.views.special_case_2003'),  6# "/articles/2003" -> no match need "2003/"7(r'^articles/(\d{4})/$', 'news.views.year_archive'), 8# ordering matters9# "/articles/2003/" -> news.views.special_case_2003, not news.views.year_archive(2003)10(r'^articles/special/(?P<year>\d{4})/$', 'news.views.year_archive'), 11# "/articles/special/2003" -> news.views.year_archive(request, year='2003')12(r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'), 13(r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'), 14# "/articles/2003/03/3/" -> news.views.article_detail(request, '2003', '03', '3')15)16 urlpatterns+=patterns('sports.views', # append like a list 17(r'^sports/2003/$', 'some_function'), 18# "/sports/2003/" -> sports.views.some_function(request)19)2021# Generic actions are useful if you are doing something generic such as:22# by default {'extra_context':{}}, add more context into extras if necessary23 urlpatterns+=patterns('django.views.generic.simple',  24(r'^page_new/(?P<id>\d+)/$', 'direct_to_template', {'template': 'page_detail.html'}),) 25 urlpatterns+=patterns('django.views.generic.simple',  26(r'^page/(?P<id>\d+)/$', 'redirect_to', {'url': '/page_new/%(id)s/'}},) 27 urlpatterns+=patterns('django.views.generic.list_detail',  28(r'^page/all/$', 'object_list', {'queryset':Pages.objects.all() }),) 29# default: {'paginate_by':'infinity' , 'page':'1',30# 'template_name':'app/model_list.html' }31 urlpatterns+=patterns('django.views.generic.list_detail',  32(r'^page/all/(?P<id>\d+)/$', 'object_detail', {'queryset':Pages.objects.all(), 'object _id':id}),) 33# default: {'paginate_by':'infinity' , 'page':'1',34# 'template_name':'app/model_detail.html' }35 urlpatterns+=patterns('django.views.generic.create_update',  36(r'^...$', 'create_object', {'model':SomeModel
  87. or
  88.  'form_class':SomeForm}),) 37# default: {'post_save_redirect':object.get_absolute_url(), 'login_required':False,38# 'template_name':'app/model_form.html' }39 urlpatterns+=patterns('django.views.generic.create_update',  40(r'^...$', 'update_object', {'model': / 'form_class':, 'object_id':SomeID}),) 41# default: {'post_save_redirect':object.get_absolute_url(), 'login_required':False,42# 'template_name':'app/model_form.html' }43 urlpatterns+=patterns('django.views.generic.create_update',  44(r'^...$', 'delete_object', {'model': / 'form_class':, 'object_id':SomeID}),) 45# default: {'post_save_redirect':object.get_absolute_url(), 'login_required':False,46# 'template_name':'app/model_confirm_delete.html' }4748# Parents are good for subdividing the work49 urlpatterns+=patterns('', # use include to add child url matchers: 50(r'^weblog/(?P<idName>\w+)/',include('mysite.app.url')), 51)52# in file app/url.py:53
  89. from
  90. django.conf.urls.defaults
  91. import
  92.  *54 urlpatterns=patterns('app.views', 55(r'^$', 'blog.index'),  56# "/weblog/me/" -> app.views.blog.index(request, idName='me')57(r'^post/(?P<postIndex>\d+)$', 'post.show'), 58# "/weblog/me/12" -> app.views.post.show(request, idName='me', postIndex='12')59(r'^details/$', 'blog.details', {'extraData', 'foo!'}) 60# "/weblog/details/" -> app.views.blog.details(request, idName='me', extraData='foo!')61(r'^post/(?P<pid>\d+)/comment/(?P<cid>\d+)/$', 'post.show', {'gotoComment', 'true'}, "w eblog-viewComment"),62# "/weblog/post/1/comment/1/" -> app.views.blog.details(request, idName='me', pid='1',cid='1', gotoComment='true')
  93. - 1 -
  94.  
  95. django_url_cheat.txtPage 2 of 2 Aug/2008
  96. 63# the template tag {% url weblog-viewComment pid=1,cid=1 %} returns "/weblog/post/1/comment/1/"64)6566# often you will write one function which has a default parameter to save code:67 urlpatterns=patterns('app.views', 68(r'^$', 'blog.index'),  69(r'^/(?P<postIndex>\d+)/$', 'blog.index')) 70
  97. def
  98.  index(request,postIndex='1') 71....7273# often we want to find a url that will execute a function with some parameters74# we would use {% url function args %} in a template. in code we would use:75
  99. from
  100. django.core.urlresolvers
  101. import
  102. reverse76 reverse(viewname,urlconf=
  103. None
  104. ,args=
  105. None
  106. ,kwargs=
  107. None
  108. )77
  109. def
  110.  myview(request): 78
  111. return
  112. HttpResponseRedirect(reverse('weblog-viewComment',args='pid=1,cid=1')) 7980# regular reference:81# . any char82# ^ start of string $ end of string83# * 0 or more of preceding + 1 or more of preceding84# ? 0 or 1 of preceding (?!..) matches when it doesnt match ..85# *? 0 or more, minimal match +? 1 or more, minimal match86# {m} exactly m of preceding {m,n} between m to n of preceding87# [..] eg. [abc],[a-z],[0-9a-z] [^..] matches if doesn't match [..]88# (..) groups what's inside (?=..) matches .. but doesn't consume it89# \d [0-9] (decimal digit) \D [^0-9] (non-digit)90# \w [a-zA-Z0-9_] (alphanumeric) \W [^a-zA-Z0-9_] (non-alphanumeric)91# \s [ \t\n\r\f\v] (whitespace) \S [^ \t\n\r\f\v] (non-whitespace)9293# Request and Response Object94
  113. def
  114.  index(request,index='1') 95 request.path# /weblog/me/ 96 request.method# either 'GET', 'POST', 'HEAD', ... 97 request.GET['someVarName'] # whatever it should be 98 request.GET['someVarName', 'default'] # if it doesn't exist then default. also for POST 99 request.POST['someVarName'] 100 request.R
  115.  
  116. EQUEST['someName'] # searches GET then FILES 101 request.COOKIES['attributeName'] 102 request.FILES['someFilename'] # request.POST does not have files 103# includes methods: read(num_bytes=...), chunk() and attrs: file_name, file_size104 request.META['someMetaName']  105# includes: CONTENT_LENGTH, CONTENT_TYPE, HTTP_ACCEPT_ENCODING, SERVER_PORT,106# HTTP_ACCEPT_LANGUAGE, HTTP_HOST, HTTP_REFERER, HTTP_USER_AGENT,107# QUERY_STR
  117.  
  118. ING, R
  119.  
  120. EMOTE_ADDR, R
  121.  
  122. EMOTE_HOST, R
  123.  
  124. EQUEST_METHOD, SERVER_NAME,108 request.user# object: django.contrib.auth.models.User 109 request.get_full_path() # includes any stuff after the last directory / 110 request.build_absolute_uri() # includes a http://www.. bit that is read from their side 111 request.is_ajax() # major ajax libraries send a signal that a query is for ajax
  125.  
  126. See also [http://www.djangoproject.com/documentation/templates/ templates for designers].
  127.  
  128.  
  129. django_forms_cheat.txtPage 1 of 2 Aug/2008
  130. 1# Simple Form with standard widgets.2
  131. from
  132. django
  133. import
  134. forms3
  135. class
  136.  ContactForm(forms.Form): 4 subject=forms.CharField(max_length=100) 5 message=forms.CharField() 6 sender=forms.EmailField() 7 cc_myself=forms.BooleanField(required=
  137. False
  138. ) # required=True by default89# Form with non-standard widget used10
  139. class
  140.  CommentForm(forms.Form): 11 name=forms.CharField(widget=forms.TextInput(attrs={'class':'special'})) 12 url=forms.URLField() 13 comment=forms.CharField(widget=forms.TextInput(attrs={'size':'40'})) 1415# Using forms16 f=ContactForm() # unbound - no data 17 data= {'subject': 'hello', 18'message': 'Hi there', 19'sender': 'foo@example.com', 20'cc_myself':
  141. True
  142. ,21'extra_field': 'foo'} 22 f=ContactForm(data) # bound - has data 23 f.is_valid() # validate 24 f.cleaned_data# returns a dictionary of the data - note: extra_field is dropped 2526# outputting html data all outputs automatically give labelled ids27 f.as_p() # renders as paragraphs 28 f.as_ul() # renders as dot-points (no <ul>) 29 f.as_table()  3031# Mapping forms to models32
  143. class
  144.  BlogForm(forms.ModelForm): 33# name = CharField(widget=forms.TextInput()) # you can override any field if you wish34
  145. class
  146.  Meta:35 model=Blog# where Article is something that inherits model.Model 36 fields= ('name',) # 'fields' specifies visible fields - so can't edit tagline, etc 37# exclude = ('tagline', 'bestEntry') # this also works, chose 'fields' or 'exclude'3839 form1=BlogForm() # just like a normal form. all normal form methods available 40 myblog=Blog.objects.get(id=1) 41 form2=BlogForm(instance=myblog) # just like normal binding 42 form2.save() # generate a model, then inserts it into db, or updates db 43# creating a new blog via a form44 b=Blog() 45 form3=BlogForm(request.POST,instance=b) 46 new_blog=form3.save(commit=
  147. False
  148. ) # generates a model, but doesn't insert into db47 new_blog.tagline= ... # since the form excluded this field, it must be filled before savin g48 new_blog.save() # saves the generated model 49 f.save_m2m() # saves many-to-many data - this is required only if you have commit=False 5051# Sample use of forms:52
  149. def
  150.  contact(request): 53
  151. if
  152. request.method== 'POST': 54 form=ContactForm(request.POST,request.FILES) 55# the second parameter is optional56
  153. if
  154. form.is_valid(): 57# Do form processing here...58
  155. return
  156. HttpResponseR
  157.  
  158. edirect('/url/on_success/') 59
  159. else
  160. :60 form=ContactForm() 61
  161. return
  162. render_to_response('contact.html', {'form':form}) 6263# you can write your own forms if you really want to:64# see django_template_cheat.txt
  163. - 1 -
  164. django_forms_cheat.txtPage 2 of 2 Aug/2008
  165. 65<form method="post"action=""> 66<dl> 67{%
  166. for
  167. field
  168. in
  169. form%}68<dt>{{field.label_tag}}{%
  170. if
  171. field.field.required%}*{%endif%}</dt> 69<dd>{{field}}</dd> 70{%
  172. if
  173. field.help_text%}<dd>{{field.help_text}}</dd>{%endif%} 71{%
  174. if
  175. field.errors%}<dd
  176. class
  177. ="myerrors">{{field.errors}}</dd>{%endif%} 72{%endfor%} 73</dl> 74<input type="submit" /> 75</form> 7677# Writing custom widgets means supplying a render function78
  178. from
  179. django.template.loader
  180. import
  181. render_to_string79
  182. class
  183.  CalendarWidget(forms.Widget):  80
  184. def
  185.  render(self,name,value,attrs=
  186. None
  187. ):81
  188. return
  189. render_to_string("widget/CalendarWidget.html",locals()) 82
  190. class
  191.  Media:83 css= {'all': ('pretty.css',)} 84 js= ('animations.js', 'actions.js') 8586
  192. class
  193.  BirthdayForm(forms.Form): 87 name=forms.CharField(max_length=100) 88 birthday=forms.DateField(widget=CalendarWidget) 8990# Field Type Reference91 BooleanField,CharField,ChoiceField,DateField,DateTimeField,DecimalField,  92 EmailField,FileField,FilePathField,FloatField,ImageField,IntegerField,  93 IPAddressField,MultipleChoiceField,NullBooleanField,RegexField,TimeField,  94 URLField9596# Field Argument Reference97 required,label,initial,widget,help_text,error_messages 9899# Widget Type Reference100 TextInput,PasswordInput,HiddenInput,FileInput,DateTimeInput,Textarea,  101 CheckboxInput,Select,SelectMultiple,RadioSelect,CheckboxSelectMultiple,  102 SplitDateTimeWidget
  194. django templates cheat sheet
  195. Ratings: (1)|Views: 12,906|Likes: 58
  196. Published by windoze007
  197. A concise 3 page cheat sheet of django's templates
  198. See more
  199.  
  200. django_template_cheat.txtPage 1 of 3 Aug/2008
  201. 1######################Rendition of django html templates2
  202. from
  203. django.template
  204. import
  205. Context,Template3 t=Template("My name is {{ my_name }}.") 4 c=Context({"my_name": "adrian"}) 5 t.render(c) # outputs "My name is Adrian" 6 c=Context({"my_name": "dolores"}) 7 t.render(c) # outputs "My name is dolores" 89 t=Template("My name is {{ person.first_name }}.") 10# when render meets a "." it will first try person["first_name"]11 c=Context({"person": {"first_name": "Joe", "last_name": "Johnson"}}) 12# then person.first_name13
  206. class
  207. PersonClass:
  208. pass
  209. 14 p=PersonClass() 15 p.first_name= "Joe" 16 c=Context({"person":p}) 17# then person.first_name()18
  210. class
  211. PersonClass2:19
  212. def
  213. first_name(self): 20
  214. return
  215. "Joe"21 p=PersonClass2() 22 c=Context({"person":p}) 23# then person[first_name]24 c=Context({"person": ["Samantha", "Ron", "Joe"], 'first_name': 2}) 2526 c=Context({"name": "david"}) 27 c['name'] 28
  216. del
  217. c['name'] 29 c['name']="jack" 3031#often you want modules to automatically add some variables into your context:32
  218. from
  219. django.template
  220. import
  221. RequestContext33
  222. def
  223. extraProcessor(request): 34
  224. return
  225. {'misc_extra_dictonary': 'here'} 35 c=RequestContext(request, {'name': 'david',},extraProcessor) 36#c will be populated with extra vars37#it will read the settings.py for TEMPLATE_CONTEXT_PROCESSORS and execute them all38#modules are under django.core.context_processors39#include auth:supporting users, debug, i18n, media, request:include request in context40#any function that takes a HttpR
  226.  
  227. equest and returns a dictionary can be used4142#often you want to load html pages:43
  228. from
  229. django.template.loader
  230. import
  231. get_template,select_template44 t=get_template(template_name) #load file or exception 45 t=select_template(template_name_list) #load first in list that exists 46#it will only load from TEMPLATE_DIRS in settings.py4748#often you want to save time not doing all this context, template stuff:49
  232. from
  233. django.template.loader
  234. import
  235. render_to_string50 rendered=render_to_string('my_template.html', { 'foo': 'bar' }) 5152#often you want to write your own filters and tags53#but right now you don't know what filters and tags are yet....5455######################Sample page base_generic.html56{# this is a comment #}5758{%load custom_module1 custom_module2%} 59{# loads custom python filter and tag modules#}6061<html> 62<head> 63<link rel="stylesheet"href="style.css" /> 64<title>{%block title%}David Website{%endblock%}</title>  65{# defining blocks will allow you to replace them later #}
  236. - 1 -
  237.  
  238. django_template_cheat.txtPage 2 of 3 Aug/2008
  239. 66</head> 67<body> 68<div id="sidebar"> 69{%block sidebar%} 70<ul> 71<li><a href="/">Home</a></li> 72<li><a href="/blog/">Blog</a></li> 73</ul> 74{%endblock%} 75</div> 7677<div id="content"> 78{%block content%}{%endblock%} 79</div> 8081<div id="disclaimer"> 82{%block disclaimer%}Copyright David{%endblock david%} 83{%include"legals/extraDisclaimer.html" %}  84{# renders that html into this page, passes current context #}85</div> 8687{%
  240. if
  241. wantDebug%}88{%debug%}{%enddebug%} 89{%endif%} 90</body> 91</html> 9293######################Sample page extended.html94{%extends"base_generic.html" %} 95{# if you render this page, it will render the base_generic.html #}96{# with each block that is defined here replacing that of the parent #}9798{%load custom_module2%} 99{# note that if your parent loads a module, you don't have it #}100101{%block title%}{{section.title}}{%endblock%} 102{# replace the block called "title" in base_generic #}103{# reads variable called section from the context #}104{# searches section["title"],section.title,section.title(),section[title] #}105{# in that exact order #}106107{# unreplaced blocks from base_generic.html, such as 'sidebar' are kept #}108109{%block content%} 110{%spaceless%} {# removes useless whitespace from the html below #} 111<h1>{{section.title}}</h1>  112{%
  242. for
  243. story
  244. in
  245. story_list%} 113<h2 color:{%cycle'red' 'blue' %}>  114{# each time the tag is read, it will output the next item #}115{{forloop.counter}}  116{# prints the loop counter #}117{# also: counter0, revcounter/0, first, last, parentloop.counter) #}118<a href="{{ story.get_absolute_url }}">  119{{story.headline|upper|capfirst}}  120{# the filter uppercases then captalises first letter #}121</a> 122</h2> 123<p>{{story.tease|cut:"\n"|truncatewords:"100" }}</p>  124{# the filter removes \n and then gets first 100 words #}125{{story.first_comment}}  126{# by default the variable is escaped #}127{# < > ' " & are converted into html character codes #}128129{{story.comment_list|first}}  130{{story.comment_list|join:", "}}
  246. - 2 -
  247. DJNGL spa
  248. Mini_django.py
  249. ==============
  250.  
  251. An entire django app in a single file. Updated from [here](http://olifante.blogs.com/covil/2010/04/minimal-django.html) to use Django trunk.
  252.  
  253. pico
  254. ====
  255. This started off to see what the absolutely smallest requirements needed to run a Django project. Run the [pico_django.py](https://github.com/readevalprint/mini-django/blob/master/pico_django.py) with `$ PYTHONPATH=. django-admin.py runserver 0.0.0.0:8000 --settings=pico_django` and go to http://localhost:8000
  256.  
  257. Or with uwsgi in production:
  258.  
  259.     $ uwsgi --http :8000 -M --pythonpath=. \
  260.     --env DJANGO_SETTINGS_MODULE=pico_django \
  261.     -w "django.core.handlers.wsgi:WSGIHandler()"
  262.  
  263.  
  264. pico_django.py
  265. =============
  266.  
  267.  
  268.     from django.http import HttpResponse
  269.     from django.conf.urls import url
  270.    
  271.     DEBUG = True
  272.     ROOT_URLCONF = 'pico_django'
  273.     DATABASES = {'default': {}}
  274.    
  275.    
  276.     def index(request, name):
  277.         return HttpResponse('Hello {name}!'.format(name=(name or 'World')))
  278.    
  279.     urlpatterns = (
  280.         url(r'^(?P<name>\w+)?$', index)
  281.     )
  282.    
  283.     SECRET_KEY = "not so secret"
  284.    
  285. mini
  286. ====
  287. Soon pico needed a little more spice, so it got some template loading and then because I'm lazy I made the new version directly runnable.
  288.  
  289. Run the [mini_django.py](https://github.com/readevalprint/mini-django/blob/master/mini_django.py) with `$ python ./micro_django.py` and go to http://localhost:8000/Foo
  290.  
  291. mini_djanog.py
  292. ==============
  293.  
  294.    '''
  295.     Run this with `$ python ./miny_django.py runserver` and go to http://localhost:8000/
  296.     '''
  297.    import os
  298.    import sys
  299.    from django.conf import settings
  300.    
  301.    from django.conf.urls import patterns
  302.    from django.http import HttpResponse
  303.    
  304.    
  305.    # this module
  306.    me = os.path.splitext(os.path.split(__file__)[1])[0]
  307.    # helper function to locate this dir
  308.    here = lambda x: os.path.join(os.path.abspath(os.path.dirname(__file__)), x)
  309.    
  310.    # SETTINGS
  311.    DEBUG = True
  312.    ROOT_URLCONF = me
  313.    DATABASES = {'default': {}}  # required regardless of actual usage
  314.    TEMPLATE_DIRS = (here('.'), )
  315.    SECRET_KEY = 'so so secret'
  316.    
  317.    if not settings.configured:
  318.        settings.configure(**locals())
  319.    
  320.    # Settings must be configured before importing
  321.    from django.views.decorators.csrf import csrf_exempt
  322.    
  323.    
  324.    # VIEW
  325.    @csrf_exempt
  326.    def index(request):
  327.        return HttpResponse("Hello from mini_django.py")
  328.    
  329.    
  330.    # URLS
  331.    urlpatterns = patterns('', (r'^$', index))
  332.    
  333.    if __name__ == '__main__':
  334.        # set the ENV
  335.        sys.path += (here('.'),)
  336.        # run the development server
  337.        from django.core import management
  338.        management.execute_from_command_line()
  339.  
  340.  
  341. Dependencies
  342. ===========
  343. * python
  344. * django
  345.  
  346. Install
  347. ======
  348. 1. Install [django](http://docs.djangoproject.com/en/dev/intro/install/)
  349. 2. get the [code](https://github.com/readevalprint/mini-django/raw/master/mini_django.py) `wget https://github.com/readevalprint/mini-django/raw/master/mini_django.py`
  350. 3. run it `$ python ./mini_django.py`
  351. 4. open browser http://localhost.com/Foo
  352.  
  353. License
  354. =======
  355. As-is. Public Domain. Don't blame me.
  356.  
  357. Author
  358. ======
  359. Tim Watts (tim@readevalprint.com)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement