Login

All snippets

Snippet List

cron/console bootstrap django

Call this function as the first thing in your cron, or console script; it will bootstrap Django, and allow you to access all of the Django modules from the console, with out using 'python manage.py shell' Examples: # A script within your django project. from django_bootstrap import bootstrap bootstrap(__file__) --- or --- # A cron script located outside of your django project from django_bootstrap import bootstrap bootstrap("/path/to/your/project/root/")

  • django
  • console
  • cron
  • bootstrap
Read More

page_link

To make page links like below: Prev 1 ... 23 24 25 26 27 ...221 Next Use like this , "bbs_posting_list" is the name of url {% page_link "bbs_posting_list" page pages %}

  • page
Read More

Template tag to sort a list of links

Sorts a list of HTML anchor tags based on the anchor's contents. This is useful, for example, when combining a static list of links with a dynamic list that needs to be sorted alphabetically. It ignores all attributes of the HTML anchor. {% load anchorsort %} {% anchorsort %} <a href="afoo.jpg">Trip to Fiji</a> <a href="bfoo.jpg">Doe, a deer, a female deer!</a> {% for link in links %} <a class="extra" href="{{ link.href|escape }}">{{ link.name|escape }}</a> {% endfor %} {% endanchorsort %} Note that case (capital vs. lower) is ignored. Any HTMl within the node itself **will not be removed**, so sorting `<a>Bar</a><a><strong>Foo</strong><a/>` will sort as `<a><strong>Foo</strong></a><a>Bar</a>` because `<` is logically less than `b`.

  • template
  • sort
  • anchor
  • a
Read More

I18n URLs via Middleware

This is an example middleware that is highly inspired by how Symfony handles [i18n in URLs](http://www.symfony-project.com/book/trunk/13-I18n-and-L10n#Changing the Culture for a User). You basically set a (?P<dj_culture>[\w-]+) pattern in your URL and this middleware will determine the language to use for the i18n toolkit for Django. It also removes the dj_culture parameter after dealing with it, so that you don't have to change all the views you want this middleware to work with.

  • middleware
  • i18n
  • url
Read More

Yet another SQL debugging facility

Inspired by http://www.djangosnippets.org/snippets/159/ This context processor provides a new variable {{ sqldebug }}, which can be used as follows: {% if sqldebug %}...{% endif %} {% if sqldebug.enabled %}...{% endif %} This checks settings.SQL_DEBUG and settings.DEBUG. Both need to be True, otherwise the above will evaluate to False and sql debugging is considered to be disabled. {{ sqldebug }} This prints basic information like total number of queries and total time. {{ sqldebug.time }}, {{ sqldebug.queries.count }} Both pieces of data can be accessed manually as well. {{ sqldebug.queries }} Lists all queries as LI elements. {% for q in sqldebug.queries %} <li>{{ q.time }}: {{ q }}</li> {% endfor %} Queries can be iterated as well. The query is automatically escaped and contains <wbr> tags to improve display of long queries. You can use {{ q.sql }} to access the unmodified, raw query string. Here's a more complex example. It the snippet from: http://www.djangosnippets.org/snippets/93/ adjusted for this context processor. {% if sqldebug %} <div id="debug"> <p> {{ sqldebug.queries.count }} Quer{{ sqldebug.queries|pluralize:"y,ies" }}, {{ sqldebug.time }} seconds {% ifnotequal sql_queries|length 0 %} (<span style="cursor: pointer;" onclick="var s=document.getElementById('debugQueryTable').style;s.display=s.display=='none'?'':'none';this.innerHTML=this.innerHTML=='Show'?'Hide':'Show';">Show</span>) {% endifnotequal %} </p> <table id="debugQueryTable" style="display: none;"> <col width="1"></col> <col></col> <col width="1"></col> <thead> <tr> <th scope="col">#</th> <th scope="col">SQL</th> <th scope="col">Time</th> </tr> </thead> <tbody> {% for query in sqldebug.queries %}<tr class="{% cycle odd,even %}"> <td>{{ forloop.counter }}</td> <td>{{ query }}</td> <td>{{ query.time }}</td> </tr>{% endfor %} </tbody> </table> </div> {% endif %}

  • sql
  • debug
  • queries
  • db
  • database
  • contextprocessor
Read More

Markup Selection in Admin

This method lets you define your markup language and then processes your entries and puts the HTML output in another field on your database. I came from a content management system that worked like this and to me it makes sense. Your system doesn't have to process your entry every time it has to display it. You would just call the "*_html" field in your template. Requires: Django .96 [Markdown](http://cheeseshop.python.org/pypi/Markdown/1.6 "Python Package Index: Markdown") [Textile](http://cheeseshop.python.org/pypi/textile "Python Package Index: Textile")

  • admin
  • model
  • markup
  • markdown
  • textile
Read More

Email on new comments

In response to [#366](/snippets/366/), this is a subclass of the `CommentModerator` class from `comment_utils` which does nothing except email the "owner" of an object whenever a new comment is posted on it; all other moderation options remain inactive.

  • email
  • comments
Read More

Email on new comments

I know ubernostrum has the nice comment_utils, but I need something that would notify the owner of the comment's content object (where the model has a foreignkey field to django.contrib.auth.models.User), but I didn't need all the moderation stuff. I stuck this in my models.py, where YOURMODEL is the name of the model object with comments attached, and a user field.

  • email
  • comments
Read More

Send large files through Django, and how to generate Zip files

This snippet demonstrates how you can send a file (or file-like object) through Django without having to load the whole thing into memory. The FileWrapper will turn the file-like object into an iterator for chunks of 8KB. This is a full working example. Start a new app, save this snippet as views.py, and add the views to your URLconf. The send_file view will serve the source code of this file as a plaintext document, and the send_zipfile view will generate a Zip file with 10 copies of it. Use this solution for dynamic content only, or if you need password protection with Django's user accounts. Remember that you should serve static files directly through your web server, not through Django: http://www.djangoproject.com/documentation/modpython/#serving-media-files

  • sendfile
  • zipfile
  • tempfile
  • temporaryfile
  • filewrapper
Read More

Custom mod_python AuthenHandler

This handler is useful if you serve static/media files directly from Apache only to authenticated users. It checks if a user is not anonymous (and therefore logged in) and redirects to the login site if needed. The following apache config activates the handler: <Location "/site_media/company1"> #SetHandler None ##Uncomment if you serve static files in the same virtual host PythonOption DJANGO_SETTINGS_MODULE mysite.settings PythonAuthenHandler mysite.myhandler PythonPath "['/path/to/project'] + sys.path" Require valid-user </Location>

  • apache
  • mod_python
  • auth
  • static
Read More

Support for {% macro %} tags in templates, version 2

Tag library that provides support for *macros* in Django templates. **Usage example:** **0)** Save this file as <yourapp>/templatetags/macros.py **1)** In your template load the library: {% load macros %} **2)** Define a new macro called 'my_macro' with parameter 'arg1': {% macro my_macro arg1 %} Parameter: {{ arg1 }} {% endmacro %}` **3a)** Use the macro with a String parameter: {% usemacro my_macro "String parameter" %} **3b)** or with a variable parameter (provided the context defines 'somearg' variable, e.g. with value "Variable parameter"): {% usemacro my_macro somearg %} **3c)** **!!NEW!!** `usemacro` now also supports filters attached to parameters: {% usemacro my_macro "lowercase parameter"|upper %} Output of the above code would be: Parameter: String parameter Parameter: Variable parameter Parameter: LOWERCASE PARAMETER **4)** **!!NEW!!** Alternatively save your macros in a separate file, e.g. "mymacros.html" and load it into the current template with: {% loadmacros "mymacros.html" %} Macros can take *zero or more arguments* and both context variables and macro arguments are resolved in macro body when used in `{% usemacro ... %}` tag. Bear in mind that Macros are local to each template file and are not inherited through `{% extends ... %}` blocks.

  • template
  • tag
  • macro
  • usemacro
  • loadmacros
Read More

Hierarchical page slugs

This allows for urls in the form of `/grandparent-slug/parent-slug/self-slug/` where the number of parent slugs could be 0 to many. You'll need to make sure that it is your last urlpattern because it is basically a catch-all that would supersede any other urlpatterns. Assumes your page model has these two fields: * `slug = models.SlugField(prepopulate_from=("title",), unique=True)` * `parent = models.ForeignKey("self", blank=True, null=True)`

  • slug
  • url
Read More

Add parameters to the current url

Often a page contains a link to itself, with an additional parameter for in the url. E.g. to sort the page in a different way, to export the data into another format, etc... This tag makes this easy, avoiding any hardcoded urls in your pages.

  • url
  • parameter
Read More

Revisiting Pygments and Markdown

A variation on a theme, inspired by [snippet 39][39] and [snippet 119][119]. The intent is to provide a more generic and simple mechanism for combining [Markdown][markdown] with [Pygments][pygments]. Common scenarios could include blogging or commenting. Snippet 119 seemed too specific and perhaps not as efficient, needing to process the HTML twice to accomplish it's ends. The one snag in the implementation is the need to use a tag other than `code` as a wrapper. See the comments for details. You will need the [BeautifulSoup][soup] module installed. Sample usage: from django.db import models class Blog(models.Model): '''Bare bones blogging model''' title = models.CharField(maxlength=255) slug = models.SlugField(maxlength=255, prepopulate_from=('title',)) pub_date = models.DateTimeField() # the cooked view, cached for quick retrieval blog = models.TextField() # the raw markdown-encoded text, saved for subsequent edits markdown = models.TextField() def save(self): from datetime import datetime if not self.id and not self.pub_date: self.pub_date = datetime.now() self.blog = pygmented_markdown(self.markdown) super(Blog, self).save() [39]: http://www.djangosnippets.org/snippets/39/ [119]: http://www.djangosnippets.org/snippets/119/ [soup]: http://www.crummy.com/software/BeautifulSoup/ [markdown]: http://www.freewisdom.org/projects/python-markdown/Installation [pygments]: http://pygments.org/

  • pygments
  • beautifulsoup
  • markdown
Read More

3110 snippets posted so far.