Login

All snippets written in Python

Snippet List

Smart i18n date diff (twitter like)

This snippet display a human readable date diff. You give it the your date in parameter and the diff with datetime.datetime.now() is returned. The diff must be positive to be more accurate (future dates are not supported) Usage: {{ status.created_at|date_diff }} Will give something like: less than 1 minute ago 13 minutes ago 1 hour ago etc. Based on [Fuzzy Date Diff Template Filter](http://www.djangosnippets.org/snippets/1347/)

  • datetime
  • i18n
  • date
  • diff
Read More

Complex Form Preview

Problem ======= The FormPreview class provided by contrib.formtools helps automate a common workflow. You display a form, then force a preview, then finally allow a submit. If the form gets tampered with, the original form gets redisplayed. Unfortunately, this class can only be used when you have an html form that is backed by exactly one Django form. No formsets, no html forms backed by more than one Django form. Solution ======== I was asked to create exactly this sort of workflow for a highly complex form + formset. The ComplexFormPreview class provides a base class to help with this problem. As with FormPreview, you must override a few functions. Code ==== The abstract ComplexFormPreview class can live anywhere on your python path. Import it and subclass is exactly like you would contrib.formtools FormPreview. The self.state dictionary is passed to all response calls as the context for your templates. Add any objects you need in your template to this dictionary. This includes all forms, formsets, and any additional variables you want in your template context. Override the parse_params if you need to get any args/kwargs from your url. Save these values in self.state if you want them in your template context. Override the init_forms method to do setup for all of your forms and formsets. Save all your forms in self.state. You should provide a unique prefix for all forms and formsets on the page to avoid id collisions in html. *VERY IMPORTANT NOTE*: init_forms is called with a kwargs dictionary. You need to pass **kwargs to all of your form definations in init_forms. This is how the POST data is going to be passed to your forms and formsets. *VERY IMPORTANT NOTE No. 2*: all of the validation is handled inside the class - all forms will be found and validated, and we will only proceed when everything is found to be valid. This means that you can use the class as a view directly, or provide a thin wrapper function around it if you want. Override the done method to handle what should be done once your user has successfully previewed and submitted the form. Usually, this will involve calling one or more save() calls to your various forms and formsets. Because you now have multiple forms, the default contrib.formtools templates don't work. You must make custom templates that reference all of your various forms. The stage_field, hash_field, and hash_value fields are used exactly like the formtools examples. Follow the basic layout demonstrated in the example templates, and substitute your custom forms for the default form. Example views.py ================ The views.py demonstrated here has many hooks into my project, including using some [complex formset classes](http://www.djangosnippets.org/snippets/1290/). It won't work for you without being customized, but it will demonstrate how to override the default ComplexFormPreview.

  • form
  • preview
  • formset
  • formtools
Read More

soaplib service integration 2

Based on our [first version of soaplib service integration](http://www.djangosnippets.org/snippets/979/), this second one adds Basic Auth with credentials specified in settings. It can be tested with [django soaplib test cliente](http://www.djangosnippets.org/snippets/1406/)

  • soap
  • soaplib
  • wsdl
Read More

django soaplib test client

This code *monkey patches* soaplib client to allow the usage of django test client for local web service testing (without a running server). It adds *basic* authentication.

  • soap
  • soaplib
  • test-client
Read More

Overwrite some views in settings.py

If you app defines some URLs with a name, and you want to overwrite this at project level with a different view you can use this snippet. You only need to change on line in the application code (the import statement).

  • urls
  • settings
  • reverse
Read More

simple DomainsAliasMiddleware

Permit to redirect desired domain name to the 'domain' of Site app. Useful if you have different domains name for the same website. #1. Add to your settings DOMAINS_ALIAS like this: DOMAINS_ALIAS = ( 'my-second-domain.com', 'www.my-second-domain.com', 'third-domain.com', 'www.third-domain.com', ) notice: all these domains are redirected to the **domain** db entry of Site ID. #2. add all these domains to ServerAlias directive in your vhost apache configuration. #3. enable the middleware by adding to your MIDDLEWARE_CLASSES: MIDDLEWARE_CLASSES = ( ... 'utils.middleware.domainsalias.DomainsAliasMiddleware', ... )

  • middleware
  • redirect
  • domain
Read More

streaming dump_data

`dumpdata` without `MemoryErrors`, with progress notification. Most of the real work is done by snippets [1400](http://www.djangosnippets.org/snippets/1400/) and [1401](http://www.djangosnippets.org/snippets/1401/). ./manage.py dumpdata_stream --format=xml > big_dump.xml This is basically the stock Django `dumpdata` with a few modifications. Django devs: it's hard to reuse parts of most Django management commands. A little refactoring could go a long way.

  • dumpdata
  • memoryerror
  • stream
  • dump_data
  • queryset_foreach
Read More

streaming serializer

Trying `./manage.py dumpdata` on a huge database and getting `MemoryError`s? Here's part of your solution. [Snippet 1400](http://www.djangosnippets.org/snippets/1400/) provides a queryset_foreach utility that we've found very useful. This snippet uses it on a serializer that can output to a stream, such as the XML serializer. Management command coming momentarily...

  • dumpdata
  • large
  • memoryerror
Read More

Queryset Foreach

Call a function for each element in a queryset (actually, any list). Features: * stable memory usage (thanks to Django paginators) * progress indicators * wraps batches in transactions * can take managers or even models (e.g., `Assertion.objects`) * warns about `DEBUG`. * handles failures of single items without dying in general. * stable even if items are added or removed during processing (gets a list of ids at the start) Returns a `Status` object, with the following interesting attributes * `total`: number of items in the queryset * `num_successful`: count of successful items * `failed_ids`: list of ids of items that failed

  • queryset
  • progress
  • callback
  • map
  • foreach
  • iterator
Read More

Create multiple related objects at once

The following code takes two related models and creates one user interface to for create and update operations that handles them both. It enables the creation or update of instances from both models in one shot, without having to create very complex forms. As I could not find examples for creation of related objects together, I thought this might be useful for someone.

  • forms
  • object-creation
  • related-objects
Read More

Seconds-to-Duration Template Tag

Does exactly what it says on the tin! This template tag, when implemented, converts a duration (in seconds) to a more meaningful format. It has a short and long setting, which is easy to manipulate for your needs. Apologies if something already exists like this, however I felt that writing this would be quicker than trying to find it online. As an example, given the duration 84658: Short (default): 23 hrs 30 mins 58 secs Long: 23 hours, 30 minutes and 58 seconds All the best, [Dan Ward](http://d-w.me).

  • template
  • tag
  • seconds
  • to
  • duration
Read More

Authenticate against Active Directory - LDAP (my version)

This is based on [snippet 501](http://www.djangosnippets.org/snippets/501/), with some corrections: 1. if user doesn't exist and AD.authenticate passes, then create new user - don't store password - prevent default django auth backend authentication 2. if user exists and AD.authenticate passes - django User object is updated 3. various error handling 4. fixes (some mentioned in original snippet) 5. some settings removed from settings to backend module 6. other changes (ADUser class, re-indent, logging etc.) 7. ignores problem with search_ext_s (DSID-0C090627) 8. caching connection - when invalid then re-connect and try again Note that there is also ldaps:// (SSL version) django auth backend on [snippet 901](http://www.djangosnippets.org/snippets/901/). Possible improvements: 1. define new settings param - use secured - then LDAPS (snippet 901) 2. define new settings extra ldap options - e.g. protocol version 3. fetch more data from AD - fill in user data - maybe to make this configurable to be able to update user.get_profile() data too (some settings that has mapping AD-data -> User/UserProfile data)

  • auth
  • ldap
  • active-directory
  • backend
Read More

Non-Javascript select list navigator

If you need a simple select list (picklist) containing all site categories (or some other taxonomic group) and don't want to depend on Javascript, here's how to build a simple category navigator in Django, using HttpResponseRedirect.

  • form
  • select
  • picklist
Read More

"Dynamic" form with a hidden field

This code demonstrates two simple techniques: 1. so-called "dynamic" forms, in which the form is created at run time by the model 2. using a widget (forms.widgets.HiddenInput) for a field of the form. I feel like this could be highlighted more in the documentation. You need to do something similar to get a textarea (forms.CharField(widget=forms.widgets.Textarea()) and it took me too long to figure this out. There are, no doubt, good reasons not to do what I'm doing here the way I'm doing it. Peanut gallery?

  • dynamic
  • form
  • field
  • hidden
Read More

RequiredNullBooleanField

In our situation, we want the user to choose either yes or no. The only requirement is that they fill out the form. It is _not_ required that they answer True/Yes. The BooleanField treats None and False as False; The NullBooleanField distinguishes between None and False, but it doesn't raise any validation errors. Subclassing the NullBooleanField was better than overriding the clean method on all of our NullBooleanField instances.

  • required
  • boolean
  • bool
  • boolean-field
  • null-boolean-field
Read More

2956 snippets posted so far.