Login

All snippets

Snippet List

Testing with unmanaged models

Many of my projects heavily depend on other non-django projects to create the databases. To simplify setting up a test environment, I modified the simple test runner so that it will treat all models as managed. This will also allow for easier test set up against models that point to views. You can directly populate the view with the specific data needed for the tests, instead of populating (potentially) several models.

  • model
  • test
  • managed
Read More

Template-Filter for Feedparser-Dates

A filter that changes a preparsed date from [Ultimate Feedparser](http://www.feedparser.org/) to a regular datetime instance. Now you can -for example- pass a feed parsed by feedparser to a template and do this: {% for item in feed.entries %} Title: {{ item.title }}<br /> Date: {{ item.updated_parsed|feedparsed|date:"Y-m-d" }} {% endfor %}

  • template-filter
  • datetime
  • date
  • feedparser
Read More

Dynamically add inlines

These functions use JQuery to dynamically add new entries for stacked or tabular inlines on a change form. To enable it, change the parent model to include this Javascript as well as JQuery. Here's an example: class MeetingAdmin(admin.ModelAdmin): inlines = [MeetingDonationInline, MeetingExtraInline] class Media: js = ["/media/jquery-1.3.2.min.js", "/media/dynamic_inlines.js"]

  • javascript
  • admin
  • jquery
  • inline
  • tabular
  • stacked
Read More

invalidation of cache-template-tag cache

this function invalidates a template-fragment cache bit. say you have: {% load cache %} {% cache 600 user_cache user.id %} something expensive here {% endcache %} maybe you want to force an update. With this function you can, just call: invalidate_template_cache("user_cache", user.id)

  • template
  • cache
  • invalidate
Read More

A tip for preserving GET arguments with pagination

This snippet shows a way to preserve GET arguments with pagination. Many people make mistakes to omit the query arguments besides page arguments for the pagination, and making sure correct may sphagettize your code.

  • template
  • get
  • view
  • pagination
  • arguments
Read More

Templatetag for granular permissions

If you're using [Django granular permissions](http://code.google.com/p/django-granular-permissions/), this templatetag may be useful. It enables you to check permission in templates, as mentioned in the code: {% has_row_perm user object "staff" as some_var %} {% if some_var %} ... {% endif %} To be used in `if` statements, it always saves the result to the indicated context variable. Put the snippet in row_perms.py in yourapp.templatetags package, and use `{% load row_perms %}` at your template.

  • template
  • templatetag
Read More

Email or username authentication with masquerading

This backend will allow you to have users login using either their username or the email address as it is in the User model. In addition, it will allow anyone with the staff priveleges to login as another user. The method is to user the user you wish to masquerade as (either email/username) as the username and then a string of the format *username*/*password* as the password, where *username* is the username of the staff member, and *password* is their password.

  • authentication
  • email
  • login
  • auth
  • backend
Read More

Generic AJAX app

This is based on the Admin app functionality for dispatching calls. Once you put these two files in place then add the following to urls.py: from myProject import ajax urlpatterns = patterns('', ... # Add this to the urlpatterns list (r'^ajax/(.*)', ajax.dispatcher.urls), ...) you register a function or method with a name like so: from django.contrib import ajax def myAutoCompleteCall(request): ... ajax.dispatcher.register('myAutoComplete', myAutoCompleteCall) Then you can use the url: `http://www.mysite.com/ajax/myAutoComplete` Previously I had placed this app in the django\\contrib directory because I wanted to use it in an Admin app mod. Since the release of 1.1 I was able to move it out into a standard app because of the new `formfield_overrides` property of the `ModelAdmin` class.

  • ajax
  • django
Read More

Automating URLs

This might be a bit cludgy. But the idea is to extend model definition with mixins that can help with defining standard views. So defining a new model as inheriting from Model and All, would allow automatic definition of /get /post type accessors.

  • rest
  • url
Read More

Custom CSS class in Form with template tag filter

A lot of times we need to insert a specific **CSS class** into a Form instance for it to be rendered in the template. The current method is to specify the CSS class in the Python code through the form field widget. But it would be easier for the designer to be able to specify the CSS class in the template directly. For example rather than doing this in your Python code: 'name = forms.CharField(widget=forms.TextInput(attrs={'class':'special'}))` You can do this in your template: `{{ form.name|cssclass:"special"}}` This template filter only works with Form Field instance.

  • css
  • form
  • class
Read More

Using class methods as views

This set of handlers allow one to isolate requests based on the method posted. Normally, in a view, we would do checks for request.method value and update the resource accordingly. This makes the view code pretty messy. So one way to avoid these check each time is to have a handler method (resource_handler above), that checks for the method parameter and dispatches to the handler withe the prefix <method>_handler_<suffix>. This also has the advantage of grouping related actions in a particular class. At the same time a new instance of the request handler is not created on each request (as with the google appengine handler?). Yet another advantage is by making the handler methods as class methods, the handler classes can be inherited to add further functionality to a resource "group. The disadvantage however is the inability to restrict access to a handler method to only particular methods. Eg above the "r'obja/(?P<id>[^\/]+)/delete/" would map to the delete_handler_objects if themethod was "delete" and post_handler_objects if the method was "post". However this can be worked with a different suffix passed to the handler_params method. Infact setting the suffix to "objects_delete" would result in a "delete_handler_objects_delete" handler on delete method and a Http404 on all others. Another inconvinience is the inability to detect a view handler by simply inspecting the url patterns. However, this information is carried within the handler_suffix and handler_class parameters which may infact provide greater insight into the semantics around the view handlers. Needless to say, this easily extends rest based accesses. Would greatly appreciate feedback and improvements.

  • django
  • views
  • class
  • methods
Read More

Django Class Views

After using Zope3/Grok for a little, I wondered how hard it would be to implement views as classes in Django, in a similar vain to how it's done in Grok. I came up with something rather simple but effective. It may be more appropriate if you use a template engine other than Django Templates, which allows you to call functions with arguments, but it's still useful none-the-less to encapsulate functions in a class. You could, for example, extend View to be JinjaView, just replacing render_template(). A nice extension, I imagine, would be to automatically figure out the template name as well as the path prefix for it (since you probably want it to be found under packagename/templatename.html).

  • django
  • view
  • class
Read More
Author: rmt
  • 4
  • 6

Text replacement with alternative font faces

Complex of tags and filters for easy replacement of text with alternative font faces. For browsers, who doesn`t support it by themselves. Templatetag code and documentation at [GitHub of django-headline](http://github.com/SkAZi/django-headline).

  • text
  • fonts
  • font
  • replacement
Read More

3110 snippets posted so far.