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...
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
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.
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).
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)
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.
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?
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.
This little bit of code will let you reference parts of the admin but lets you control where it returns to.
For instance, I have a list of objects in the admin and i want to have a delete link for each object. I don't want them to return to the changelist after a delete however, i want them to return to my list.
cheers
**Update:**
Never mind. See [dc's comment](http://www.djangosnippets.org/snippets/1391/#c1763) below for a much easier way to do this.
I recently had to write a template for a paginated view which displayed a serial number for each `object` in the `object_list`. I normally use `forloop.counter` for general purpose serial numbers. However this did not work with paginated views as the counter gets reset in each page. This caused the serial numbers to go from 1 to #-of-results-in-the-page and then repeat.
**Assumptions:**
The `adjust_for_pagination` filter adjusts the value of `forloop.counter` based on the current page. `Page` and `is_paginated` variables are expected to be present in the context. These should respectively denote the current page number (1 based) and if the results are paginated. `RESULTS_PER_PAGE` is currently taken from the settings file. I couldn't think of a way to pass this value also from the template.
I wanted to use Nose with Django so I came up with this.
`TEST_RUNNER = 'noserun.run_tests'` in settings.py
It does not do setup/teardown implicitly between test
methods, you need to call *nosetest.test.flush()* and
*nosetest.test.loaddata()* manually if you want that.
Enables the method names *setup* and *teardown*
The environment variable *NOSE_COVER* runs coverage
tests and *NO_DROPDB* preserves the test db.
I recently worked on an application, where I had to provide a way for users to search for objects based on user-defined properties attached to these objects. I decided to model the search form using a formset, and I thought it'd be a good idea to allow users dynamically add and remove search criteria.
The script (dynamic-formset.js) should be re-usable as-is:
1. Include it in your template (don't forget to include jquery.js first!).
2. Apply the 'dynamic-form' class to the container for each form instance (in this example, the 'tr').
3. Handle the 'click' event for your `add` and `delete` buttons. Call the `addForm` and `deleteForm` functions respectively, passing each function a reference to the button raising the event, and the formset prefix.
That's about it. In your view, you can instantiate the formset, and access your forms as usual.
This is a [Paginator Tag](http://www.djangosnippets.org/snippets/73/) for 1.x. Since the context is less overfull, the template, paginator.html, needs more logic.
Put the tag in your templatetags and the template at the root of a template-directory.
The tag will work out of the box in a generic view, other views must provide `is_paginated` set to True, `page_obj`, and `paginator`. You can get the `object_list` from the `page_obj`: `page_obj.object_list`. See [the pagination documentation](http://docs.djangoproject.com/en/1.0/topics/pagination/).