Login

All snippets

Snippet List

Repeat blocks with new context / simple Jinja-like macro system

A simple macro system that makes it possible to reuse previously defined blocks, optionally with a custom context, similar to the macro functionality in Jinja. It requires some workarounds/hacks because we cannot reach all the data from inside the django template system that we need, but it seems to work pretty well so far. It is, however, also pretty untested at this point, so use at your own risk. Examples: base.html: <!-- This is mandatory if you want to use the repeat-tag in a template. It should as placed as earily as possible. See below for how to mix with template inheritance. --> {% enablemacros %} <!-- Note that {{ param }} does not exist. --> {% block foo %} A standard django block that will be written to the output. {% if param %}{{ param }}{% endif %} {% endblock %} {% macro bar %} Pretty much the same thing as a django block (can even be overridden via template inheritance), but it's content will NOT be rendered per default. Please note that it ends with ENDBLOCK! {% if param %}{{ param }}{% endif %} {% endblock %} <!-- Render foo for the second time --> {% repeat foo %} <!-- Render foo bar the first time --> {% repeat bar %} <!-- Render both blocks again, and pass a parameter --> {% repeat foo with "Hello World" as param %} {% repeat bar with "Hello World" as param %} {% macro form %}do stuff with: {{ form }}{% endblock %} {% for form in all_forms %} {% repeat display %} <!-- will have access to {{ form }} {% endfor %} extend.html: <!-- {% extends %} requires that it be the first thing in a template, and if it is, everything except for block tags is ignored, so {% enablemacros %} won't work. Instead, use: --> {% extends_with_macros 'base.html' %} {% block foo %} Will override "foo" in base.html {% endblock %} {% block bar %} Will override the macro block "bar" in base.html. Whether this is defined as block or macro doesn't matter. {% endblock %} Todo: * This (both tags used) results in infinite recursion: {% extends_with_macros "somefile" %}{% enablemacros %}

  • templates
  • macro
  • jinja
  • repeat
  • reuse
  • variables
Read More

Load templatetag libraries via settings

In your settings file: TEMPLATE_TAGS = ( "djutils.templatetags.sqldebug", ) Make sure load_templatetags() gets called somewhere, for example in your apps __init__.py *Edit: Updated to work with templatetag libraries that use certain critical django-bits.*

  • templates
  • settings
  • tags
  • templatetags
  • conf
Read More

Javascript HTTP response

I've been using this along with [prototype](http://www.prototypejs.org) to make simple ajax calls. In essence you make the calls from the client with... new Ajax.Request('url',{parameters:{'someparam':$('someparam').value}}); return false; On the onsubmit event of a form, onclick or whatever. Note that the return false is important to prevent the page from reloading. Sending some javascript to be executed back to the client is then as simple as setting up your view to return: return HttpJavascriptResponse('alert("boing");') So, yeah, prototype does the real work and this class does little other than make it clear what our intentions are and reduce the opportunities for typos. But it works for me.

  • ajax
  • javascript
  • prototype
  • return
Read More

Enhanced "avoid widows" template filters

Building on [jcroft's snippet](http://www.djangosnippets.org/snippets/17/), here's a slightly more advanced version which has two filters, one for basic text and the other for html snippets. Usage is like so: <h2>{{ blog_entry.headline|escape|widont }}</h2> {{ blog_entry.html|widont_html }} On top of Jeff's reasons for using these filters, they are important because they help keep one of [God's commandments](http://www.ebible.com/bible/NIV/Exodus+22%3A22). ;)

  • filter
  • widows
  • typography
  • widont
Read More

Django & cache headers

This takes advantage of a recently added feature to django, being able to give it real functions as the view instead of having it be a string that is has to look up itself. It takes advantage of how decorators work and how `cache_control` works, normally you'd do something like this: @cache_control(private=True, public=False) def view_stuff(request): # ... return response Which is equal to doing `view_stuff = cache_control(private=True, public=False)(view_stuff)` after definition. `cache_control` is a function factory, more or less, which we use to our advantage.

  • cache
  • decorators
Read More

Validation for 'unique' and 'unique_together' constraints (different version)

This is a slightly different and extendend version of this snippet: http://www.djangosnippets.org/snippets/260/ Unique constraints for single fields are validated in a clean_FIELD, instead of globally in the form's clean() method, so that the error messages are correctly assigned to each field. Additionally, you can specify mappings for unique_together constraints to assign those error messages to a specific field as well (instead of having them in non_field_errors(), where they would normally be.

  • newforms
  • forms
  • validation
  • unique_together
  • unique
  • constraints
Read More

newforms: Add field-specific error in form.clean()

This is a bit of a hack, but as far as I can see currently the only way to specify a validation error that is specific to a field in form.clean(). I am aware of clean_<fieldname>, but those are difficult to use when the validation process for a field involves other fields as well, because the necessary data might at that point not be yet available in form.cleaned_data.

  • newforms
  • forms
  • validation
  • clean
Read More

Additional Change List Columns

Ever wanted to add a link or two at the end of a row in a model's change list? Say you had a model for people and a model for registrations or blog posts and you want to modify the people change list so it has a link to, say all of the registrations or blog posts for the person. Well, Django provides half of the solution already in that the example registration change_list already handles the display of all registrations tied to that person. For example, the url `/admin/registrations/registration/?person__id__exact=121` gets you to a filtered list of registrations for the person with the id of 121. This is the same url used if you use list_filter in your model definition (though setting list_filter is not required for what we're doing). Okay, so to add a link to the end of each person row in the change list, you need to create a template tag similar to "person_result_list" in the code. There, I've given an example that adds two links. Each dictionary in additional_links needs to have at least a text, sortable, and url_template attribute. The text attribute is what will display as the header to the column. url_template will be fed the id of the row object (in this example, a person id), which you can use to construct the link for each row. You could extend this if you wish, though all I ever need is the id. And the last step is to use your new template tag in a modified change_list.html in place of the default result_list tag. The example at the bottom of the code shows an example usage of the tag. Hope this makes sense and is helpful to someone!

  • template
  • admin
  • tags
  • change_list
Read More

UUIDField

UUIDField is a field which stores an uuid generated by pythons new uuid module. it's included with the python 2.5 distribution by default, but if you run an older version of python you can happily copy the file from 2.5 to django/utils/uuid.py or your project directory.

  • fields
  • field
  • uuid
Read More

sqlallall.py

A simple script to run 'manage.py sqlall' on every app in a project.

  • sql
  • manage.py
  • sqlall
Read More
Author: jkl
  • 0
  • 2

newforms self-contained login form

A simple login form that does the actual authentification itself. **Usage:** if request.method == "POST": loginform = LoginForm(request.POST) if loginform.login(): return HttpResponseRedirect(redir_url) else: loginform = LoginForm()

  • newforms
  • login
  • auth
Read More

Extended rails flash implementation

This is an extendend version of the Rails Flash implementation by Sean Patrick Hogan that supports different message types. **Setting a flash message:** request.flash.error = 'Item could not be saved' request.flash['error'] = 'Item could not be saved' request.flash['foo'] = 'bar' **Displaying a flash in the view:** <!-- show the error message --> {% if flash.error %}An error occured:{{ flash.error }}{% endif %} <!-- just show the first message found --> {% if flash %}An error occured:{{ flash }}{% endif %} <!-- show all messages --> {% for msg in flash %}{{ msg.type }}: {{ msg.msg }}{% endfor %} Note that it still works with simple strings as well. Feel free to just use it like this: request.flash = "Message" And: {% if flash %}{{ flash }}{% endif %} However, be aware that once you did this, you destroyed the Flash() dict and thus lost the extended functionality. You can use request.flash.clear() to remove all messages.

  • flash
  • messages
  • rails
Read More

Pass db.Field to newforms.Widget

Deprecated. I don't use this any more. Hi, I want decimal input which uses a comma as decimal seperator. It was quite complicated, but it works. It can be used as an example how to create an own subclass of an existing db.Field class and how to pass the dbfield to the widget, and use it in its render() method. I think my snippet is too complicated, but couldn't find a better solution. If you do, please tell me.

  • newforms
  • i18n
Read More

DRY with common model fields (another way)

Some time you want to add some common fields to a group of models, for example, in a **Generalization/Specialization** relationship. One could have a base model as the generalization class and specialized models with a foreign key to that base model with an unique attribute but I don't like it that way so, I just do this code to add some commons attributes to a lot of models. If you have many models that all share the same fields, this might be an option. The fields are added directly to each model, e.g. while they will be duplicated on the database level, you only have to define them once in your **python** code. This code is a cleaner way(I think!!!) to do it and will do the same that [this one](http://www.djangosnippets.org/snippets/317/). I hope this piece of code will be useful for you.

  • models
  • model
  • dry
  • common
Read More

3110 snippets posted so far.