Login

Most bookmarked snippets

Snippet List

MaxMind(R) GeoIP Lite geolocation models

This provides GeoDjango models for the maxmind GeoIP Lite data products. Use the corresponding [CSV import script](http://www.djangosnippets.org/snippets/328/) for data import. Requires: [GeoDjango](http://code.djangoproject.com/wiki/GeoDjango) and the [BigIntegerField patch](http://code.djangoproject.com/attachment/ticket/399/django-bigint-20070712.patch) by Peter Nixon.

  • log
  • gis
  • ip
  • geolocation
  • maxmind
  • geodjango
Read More

Hidden Forms

Have your forms descend from this BaseForm if you need to be able to render a valid form as hidden fields for re-submission, e.g. when showing a preview of something generated based on the form's contents. Custom form example: >>> from django import newforms as forms >>> class MyForm(HiddenBaseForm, forms.Form): ... some_field = forms.CharField() ... >>> f = MyForm({'some_field': 'test'}) >>> f.as_hidden() u'<input type="hidden" name="some_field" value="test" id="id_some_field" />' With `form_for_model`: SomeForm = forms.form_for_model(MyModel, form=HiddenBaseForm)

  • newforms
  • form
  • baseform
  • hidden
Read More

QLeftOuterJoins

This hack replaces all INNER JOINs inside to the LEFT OUTER JOINs (see http://code.djangoproject.com/ticket/3592 for explanation). Use: QLeftOuterJoins(Q(...) | Q(...) & (Q(...) | ....)).

  • q
  • query
  • join
  • left
  • outer
Read More

Last pages the user visited

This middleware remembers the last URLs that the user visited on your Django-site and saves them into the `request.session`. The fields are `currently_visiting` for the URL that is opened by the user and `last_visited` which is the URL before. Most of the time, you'll need only `last_visited`, as `currently_visiting` is just an implementation detail. For what is this good for? Imagine, you have to implement something like JavaScripts `history.back()` or `history.forward(-1)` but without JavaScript. Things start to get difficult when using JavaScript is not possible, for whatever reason. This snippet was created because I needed to redirect the user to the page he's been watching before clicking on the "translate" link. One other alternative would be adding the URL the user was visiting as a GET field to the "translate" link, but I hoped to find a possibility to avoid GET. This snippet works quite well as a proof of concept, the only known wart is when the user uses tabs or multible windows on the site, things get messed up. This cannot be solved, it's a restriction imposed by the design of HTTP.

  • middleware
  • session
  • user
Read More

jsonify template filter

Simple template filter to encode a variable to JSON format Usage: {% load json_filters %} {% block content %} &lt;script type="text/javascript"&gt;<![CDATA[ var items = {{ items|jsonify }}; ]]>&lt;/script&gt; {% endblock %} I'm using JsonResponse for the views but I also want to have preloaded JSON data into the page output

  • template
  • filter
  • json
Read More

Compact idiom for legacy URLs in URLconfs

Taken from the [longer description on my blog][1]: > One of the great things about Django is its simple and flexible URL handling. If your Django work, like mine, includes converting existing sites, you’ll probably be doing some URL cleanup along the way... Just plug your old/new URL pairs into `redirects`. [1]: http://e-scribe.com/news/290

  • urlconf
  • redirect
Read More
Author: pbx
  • 6
  • 9

FieldsetForm

This is FieldsetForm for rendering forms with fieldsets. This is not in anyway final version of this snippet. This is preliminary version which just works. One can easilly implement the `as_ul`, `as_p` at the end with just looking the `as_table` definition. > Content developers should group information where natural and appropriate. When form controls can be grouped into logical units, use the FIELDSET element and label those units with the LEGEND element... - [Web Content Accessibility Guidelines 1.0](http://www.w3.org/TR/WCAG10-HTML-TECHS/#forms-grouping) **Notice**: Since this uses *real* fieldset elements of HTML we had to define `form.as_table` the way it *includes* the `table` element around it. **Usage in template** {{ form }} and **not** `<table>{{ form }}</table>` **Usage in view** Following usage example is for *django.contrib.flatpage*, but naturally you can use it to whatever you want. Example assumes user knows about newforms and basics to how to use `form_for_*` functions from THIS-SNIPPETS-POSITION-IN-PYTHON-PATH import form_fieldsets ... fieldsets = form_fieldsets( (None, {'fields': ('url','title','content',)} ), ("Advanced options", {'fields': ('sites', 'template_name', 'registration_required',), 'classes':'collapse'}) ) ... ... forms.models.form_for_instance(flatpage, **fieldsets) ... forms.models.form_for_model(FlatPage, **fieldsets) ... Above creates two fieldsets: 1. "None" named fieldset (meaning no name is given) with fields 'url', 'title' and 'content'. 2. "Advanced options" named fieldset with fields 'sites', 'template_name' and 'registration_required' and collapse class in place. Syntax of form_fieldsets function is identical with models `class Admin: fields = (...)`, actually you can use admins exact line here with adding it like `form_fieldsets(*FlatPage.Admin.fields)` if you prefer that, although it wrecks the point of having newforms admin, if one does identical forms as in admin part. Purpose of this is not to create identical forms as in admin but to provide easy fieldsets for all views and forms. To follow DRY principle this should be part of Django and Django's newforms-admin branch should start to use some subclassing of this. But even if the newforms-admin branch never take this in, it is more DRY than without to use this in own projects, with this in place you can forget all template hazzles defining fieldset manually. **Some "counter" statemets for having this** > **S**: "But I want to define the table tag myself in template!" **A**: Well, you understod something wrong; First of all, for example, if there is something missing from the output of this table tag, you can feel free and subclass from FieldsetForm and define own as_table. Second of all, for having own table tag there can be only one reason to that, you want extra arguments, and that is TODO, but it is also easy piece. I haven't just needed extra stuff yet so they are not implemented. > **S**: "But, oh my! (newforms) admin does this already!" **A**: For the **last time** this is not meant for only newforms admin, you can use this on **any** given view or form renderition, since currently django does not give a simple way to use that handy fieldset automation in own views. And currently (9th of April, 2007) newforms admin does not do it this way. > **S**: "But, I want to use as_p, as_ul ..." **A**: Go ahead and fix them below... Should be pretty easy stuff. > **S**: "Each model should have only one fieldsets setting." **A**: I don't believe that; even if I did that is not convincing, since there are views that are not based on models, just bunch of fields, how would you define their fieldsets if it is not defined in the form renderition at the first place? This is the right place to define fieldsets. And the point of *FieldsetForm* is not just having multiple fieldsets per model, it is about *where* and *how* to render them.

  • newforms
  • admin
  • fieldset
Read More

Password Reset Form Newforms

A Change Password form that asks the user for the old password and checks the two new passwords. Whenever you instantiate the form you must pass a User object to it. ex. theform = forms.PasswordReset(request.user,request.POST)

  • newforms
  • password-reset
Read More

BritishDateField

The date field in the newforms module includes American style mm/dd/yyyy , which anyone outside the US will recognise as being complete madness. This date field behaves sensibly.

  • newforms
Read More

simple text image view

**Credit goes to** [Andrew Gwozdziewycz](http://www.23excuses.com/2006/Jun/30/simple-django-view-for-dynamic-text-replacement/) and [Jacob Kaplan-Moss](http://www.jacobian.org/writing/2006/jun/30/improved-text-image-view/) This is basically their code. Only differences: * orientation can be customized * size can be customized * GIF-Image with transparency is created Note: Because of the minimum palette that's used, the font isn't antialiased/smoothened. My url for this view looks like so: (r'^img/(?P<fontalias>\w+)/(?P<orientation>(normal|left|right))/$', 'view.text_to_image')

  • text
  • image
  • text-image-view
Read More

create_object and update_object for newforms

create_object and update_project modified to handle newforms (including FileFields). In addition, I have added some extras: 1. extra_fields - this is a dict or callable that contains additional fields to be passed to the form, for example stuff that is in the session. 2. on_success - callback called if form is valid and object created/updated, if this is not set the default behaviour is to send a redirect 3. on_failure - callback called if form is invalid, the default is to redisplay the form. Note that once newforms are finally done these functions are likely to be redundant, as generic views will be updated to use the newforms API, so use with caution.

  • newforms
  • forms
  • generic-views
Read More

Url filter middleware

How to config it ------------------ You can treat it as a micro url filter framework. Before you using it, you should setup some options about it. The option entry shoud be like this: FILTERS = ( (r'^user/(?P<user_id>\d+)/', 'apps.users.filter.check_valid_user'), ) FILTERS should be a list or tuple with two elements tuple item. The format should be like: (url_patterns, function) And url_patterns could be a single regex expression or a list/tuple regex expressions, So you can set multi regex expression in it. And the regulation is just like url dispatch, as above example, the url pattern is: r'^user/(?P<user_id>\d+)/' So you can see, you can set parameter name `user_id`, then it'll be passed to the function behind. Function can be a string format, just like above example, and it can be also a real function object. It'll only impact request. How to write filter function ------------------------------- According above example, I define a url pattern, and what to check if the user is a valid user, and if the user is visiting his own urls, so the filter function could be: from django.contrib.auth.models import User from utils.common import render_template def check_valid_user(request, user_id): if request.user.is_anonymous(): return render_template(request, 'users/user_login.html', {'next':'%s' % request.path}) try: person = User.objects.get(pk=int(user_id)) except User.DoesNotExist: return render_template(request, 'error.html', {'message':_("User ID (%s) is not existed!") % user_id}) if person.id != request.user.id: return render_template(request, 'error.html', {'message':_('You have no right to view the page!')}) I think the code is very clear. And you can use it filtermiddleware to do like user authentication check, and other checking for url. BTW, render_template is comes from [Snippets #4](http://www.djangosnippets.org/snippets/4/)

  • middleware
  • filter
  • url
Read More

Simple profile middleware

Intall -------- In your settings.py, set it in MIDDLEWARE_CLASSES. Default all the profile files will be save in ./profile folder(if there is no this directory, it'll automatically create one), and you can set a PROFILE_DATA_DIR option in settings.py, so that the profile files can be saved in this folder. How does it works ------------------- Record every request in a profile file. As you can see in the code: profname = "%s.prof" % (request.path.strip("/").replace('/', '.')) so if you request an url multi-times, only the last request will be saved, because previous profile files will be overriden. And you can find a commentted line, it'll save each request in different file according the time, so if you like that you can change the code. # profname = "%s.%.3f.prof" % (request.path.strip("/").replace('/', '.'), time.time()) and if you want to see the output, you can run below code, but you should change the filename value: import hotshot, hotshot.stats stats = hotshot.stats.load(filename) #stats.strip_dirs() #stats.sort_stats('time', 'calls') stats.print_stats()

  • middleware
  • profile
Read More

EasyFeed class

This class simplies the Feed class of django. The differences are: 1. Don't need define title and description template file 2. default feed generator class is Atom1Feed 3. According feed_url, EasyFeed can auto get the domain field, and you can also specify the domain parameter.(feed_url should be a full domain path, so you can use [Get the full request path](http://www.djangosnippets.org/snippets/41/) to get the full path of the feed url.) 4. There is a helper function render_feed() to return a response value. example --------- Feed class: class BookCommentsFeed(EasyFeed): def __init__(self, feed_url, book_id): super(BookCommentsFeed, self).__init__(feed_url) self.book_id = book_id self.book = Book.objects.get(id=int(book_id)) def link(self): return '/book/%s' % self.book_id def items(self): return self.book.comment_set.all().order_by('-createtime')[:15] def title(self): return 'Comments of: ' + self.book.title def description(self): return self.book.description def item_link(self, item): return '/book/%s/%s' % (self.book_id, item.chapter.num) def item_description(self, item): return item.content def item_title(self, item): return '#%d Comment for: ' % item.id + item.chapter.title def item_pubdate(self, item): return item.createtime def item_author_name(self, item): return item.username And the view code is: from feeds import * from utils.easyfeed import render_feed from utils.common import get_full_path def bookcomments(request, book_id): return render_feed(BookCommentsFeed(get_full_path(request), book_id))

  • feed
  • rss
Read More

3110 snippets posted so far.