Login

All snippets

Snippet List

convert plain text to html

Convert plain text to html. For example: text="""aabhttp://www.example.com http://www.example.com http://www.example.com <<< [<aaaa></aaaa>] """ print plaintext2html(text) It can convert url text to html href. And it also can convert space to &nbsp;. So if you paste python code, the indent will not lost at all. Default it'll convert \t to 4 spaces.

  • text
Read More

Avoid widows using a template filter

**Support good typography! Avoid widows! ** "Widows" are single words that end up on their own line, thanks to automatic line-breaks. This is an no-no in graphic design, and is especially unsightly in headers and other short bursts of text. This filter automatically replaces the space before the last word of the passed value with a non-breaking space, ensuring there is always at least two words on any given line. Usage is like so: {{ blog.entry.headline|widont }} It's a simple tag, but good typography is one of the hallmarks of a well-designed site that separates it from amateurish counterparts. Note: The idea and name "widont" is copped directly from [Shaun Inman](http://shauninman.com), who wrote a [similar feature for WordPress](http://www.shauninman.com/archive/2006/08/22/widont_wordpress_plugin).

  • filter
  • widows
  • templatetag
  • typography
  • shauninman
  • widont
Read More

Create OpenOffice documents

This view will enable you to generate OpenOffice documents from templates written in OpenOffice 2.x Just make sure that there is no OO tag in between your code (no change in formatting etc.). content.xml is a valid XML file, so you can do some preprocessing using xml.dom.minidom. I would also recommend caching (just save the zip file without content.xml and content.xml on its own).

  • print
  • odf
  • office
Read More

db_dump.py - for dumpping and loading data from database

Description ============= This tool is used for dump and restore database of Django. And it can also support some simple situations for Model changes, so it can also be used in importing data after the migration of Model. It includes: dump and restore. Dump ====== Command Line: python db_dump.py [-svdh] [--settings] dump [applist] If applist is ignored,then it means that all app will be dumped. applist can be one or more app name. Description of options: * -s Output will displayed in console, default is writing into file * -v Display execution infomation, default is does not display * -d Directory of output, default is datadir in current directory. If the path is not existed, it'll be created automatically. * -h Display help information. * --settings settings model, default is settings.py in current directory. It can only support Python format for now. It'll create a standard python source file, for example: dump = {'table': 'tablename', 'records': [[...]], 'fields': [...]} table' is table name in database, records is all records of the table, it's a list of list, that is each record is a list. fields` is the fields name of the table. Load(Restore) ¶ Command Line: python db_dump.py [-svdrh] [--settings] load [applist] You can refer to the above description for same option. Others is: * -r Does not empty the table as loading the data, default is empty the table first then load the data Using this tool, you can not only restore the database, but also can deal with the simple changes of database. It can select the suitable field from the backup data file according to the changed Model automatically, and it can also deal with the default value define in Model, such as default parameter and auto_now and auto_now_add parameter for Date-like field. And you can even edit the backup data file manually, and add a default key for specify the default value for some fields, the basic format is: 'default':{'fieldname':('type', 'value')} default is a dict, the key will be the field name of the table, the value will be a two element tuple, and the first element of this tuple is type field, the second element is its value. Below is a description of type field: type value description 'value' real value using the value field directly 'reference' referred field name the value of this filed will use the value of referred field. It'll be used when the field name is changed 'date' 'now'|'yyyy-mm-dd' It's a date date type, if the value field is 'now', then the value be current time. Otherwise, it'll be a string, it's format is 'yyyy-mm-dd' 'datetime' 'now'|'yyyy-mm-dd hh:mm:ss' The same as above 'time' 'now'|'hh:mm:ss' The same as above The strategy of selection of default value of a field is: first, create a default value dict according the Model, then update it according the default key of backup data file. So you can see if there is a same definition of a field in both Model and backup data file, it'll use the one in backup data file. According the process of default value, this tool will suport these changes, such as: change of field name, add or remove field name, etc. So you can use this tool to finish some simple update work of database. But I don't give it too much test, and my situation is in sqlite3. So download and test are welcome, and I hope you can give me some improve advices. project site ============= http://code.google.com/p/db-dump/

  • tool
  • dump
Read More

PyIfTag - Just like python if expression

How to use it {% pyif i == 1 %} <p>i=1</p> {% elif i == 3 %} <p>i=3</p> {% else %} <p>other</p> {% endif %} Warning: For now, django don't support elif, so you can use it. And I'v submit a patch about to fix it ( #3090 ). If the patch is accepted, you can use elif tag.

  • tag
Read More

CallTag - Just like include, but can pass parameters to it

I knew that template in myght template system can receive some parameters just like a function. And I also want to implement this function in django template. So I finish a rough one, the code is pasted here. It just like include, but in order to distinguish with "include" tag, I call it "call". So you can use it: {% call "some.html" %} This way just like include tag, and the advanced way: {% call "some.html" with "a" "b"|capfirst title="title1" %} {% call "some.html" with "c" "d" title="title2" %} So you can see, "call" tag can do like a python function, it can receive tuple parameters and key word parameters, just like the function: def func(*args, **kwargs):pass How to use it =============== test_call.html {% expr "limodou" as name %} {% call "test/test_sub.html" with "a"|capfirst "b" title="title1" %}<br/> {% call "test/test_sub.html" with "c" "d" title="title2" %} expr is also a custom tag written by me. It'll calculate a python expression and save to result to a variable. In this case, the variable it "name". test_sub.html {% for i in args %}{{ i }}{% endfor %} <h2>{{ title }}</h2> <p>{{ name }}</p> <h3>args</h3> {{ args }} <h3>kwargs</h3> {{ kwargs }} And you also can see, call tag will auto create args and kwargs context variables. I hope this will be some useful.

  • tag
Read More

ExprTag - Calculating python expression and saving the result to a variable

This tag can be used to calculate a python expression, and save it into a template variable which you can reuse later or directly output to template. So if the default django tag can not be suit for your need, you can use it. How to use it {% expr "1" as var1 %} {% expr [0, 1, 2] as var2 %} {% expr _('Menu') as var3 %} {% expr var1 + "abc" as var4 %} ... {{ var1 }} for 0.2 version {% expr 3 %} {% expr "".join(["a", "b", "c"]) %} Will directly output the result to template Syntax {% expr python_expression as variable_name %} python_expression can be valid python expression, and you can even use _() to translate a string. Expr tag also can used context variables.

  • tag
Read More

ajax protocol for data

Can be used for create a json format response data. Just like: {response:'ok', next:'nexturl', message:'response message', data:'returned data'} for success. {response:'fail', next:'nexturl', message:'response message', error:'error messages'} for failure. And there are some dump function: json - dump a python variable into json format string json_response - dump a python variable into json format string, and then use it create a HttpResponse object.

  • ajax
  • serialize
Read More

Validator for data

This module is not aimed to replace the newforms, but I would like manually write html code, and just need a pure validate module, so I write this, and many things may be similar with newforms. So if you like me would only need a pure validator module, you can use it. And it has some different features from newforms: 1. Support validator_list parameter, so you could use it just like the old manipuator class 2. Supply easy method, such as `validate_and_save()`, so you can pass a request object, and get a tuple result `(flag, obj_or_error)`, if the `flag` is `True`, then the next value is an object; and if the `flag` is `False`, then the next value is error message. 3. Each field has a `validate_and_get` method, and it'll validate first and then return the result, maybe an object or error message. Just like above. 4. SplitDateTimeField is somewhat different from the newforms. For example:: c = SplitDateTimeField('date', 'time') print c.validate_and_get({'date':'2006/11/30', 'time':'12:13'}) So the first parameter is DateField's field_name, and the second parameter is TimeField's field_name. 5. Add yyyy/mm/dd date format support 6. Support default value of a field. You can add a default value for a field, if this field is not required, and the value is *empty*, Validator will return the default value. This module is new, so many things could be changed.

  • validator
Read More

A couple of template filters for partitioning lists

People -- and by "people" I mean Jeff Croft -- often ask about how to split a list into multiple lists (usually for presenting as columns in a template). These template tags provide two different ways of splitting lists -- on "vertically", and the other "horizontally".

  • template
  • filter
  • lists
Read More

Localized URLs (www-en)

An example on how we changed our localization middleware to use www-en.<domain> instead of it being hidden in the cookie. This also changes zh-cn to cn, and zh-tw to tw in the URLs. This is only a base snippet and you will most likely need to modify it to fit your needs.

  • internationalization
  • middleware
  • il8n
  • urls
Read More

3109 snippets posted so far.