This is the "unobtrusive comments moderation" code from http://www.djangosnippets.org/snippets/112/ , but updated so it works properly with Django 1.0.
There are only a few small changes reflecting changes in the comments, contenttypes, and signals APIs.
For full background, see the original snippet:
http://www.djangosnippets.org/snippets/112/
returns a list of (argname, value) tuples
(NB: keeps ordering and is easily turned into a dict).
Params:
* tagname : the name of calling tag (for error messages)
* bits : sequence of tokens to parse as kw args
* args_spec : (optional) dict of argname=>validator for kwargs, cf below
* restrict : if True, only argnames in args_specs will be accepted
If restrict=False and args_spec is None (default), this will just try
to parse a sequence of key=val strings.
About args_spec validators :
* A validator can be either a callable, a regular expression or None.
* If it's a callable, the callable must take the value as argument and
return a (possibly different) value, which will become the final value
for the argument. Any exception raised by the validator will be
considered a rejection.
* If it's a regexp, the value will be matched against it. A failure
will be considered as a rejection.
* Using None as validator only makes sense with the restrict flag set
to True. This is useful when the only validation is on the argument
name being expected.
Filter for a list if breadcrumbs. All necessary code included but obviously only the breadcrumbs method that is needed with necessary changes for esc().
I use it as
{% load breadcrumbs %}
{{ request.path|breadcrumbs:"" }}
enclosed in an unordered html list with id="breadcrumbs"
Very simple proof-of-concept that uses the django.forms library (newforms) for validation,
and formalchemy for saving the model instance using sqlalchemy.
it can be used like this (pseudo-code):
if form.is_valid():
form.save(session=Session, app_label='Contact')
Feel free to improve the concept. Ideally, either use formalchemy or django.forms
but not both like this example. ;-)
Background
==========
Edit: This snippet doesn't make a lot of sense when Malcolm's blog is down. Read on for some history, or go [here](http://www.djangosnippets.org/snippets/1955/) to see the new trick that Malcolm taught me.
A year ago, Malcolm Tredinnick put up an excellent post about doing complex Django forms [here](http://www.pointy-stick.com/blog/2008/01/06/django-tip-complex-forms/).
I ended up reinventing that wheel, and then some, in an attempt to create a complex formset. I'm posting my (partial) solution here, in hopes that it will be useful to others.
Edit: I should have known - just as soon as I post this, Malcolm comes back with a solution to the same problem, and with slightly cleaner code. Check out his complex formset post [here](http://www.pointy-stick.com/blog/2009/01/23/advanced-formset-usage-django/).
I'll use Malcolm's example code, with as few changes as possible to use a formset. The models and form don't change, and the template is almost identical.
Problem
=======
In order to build a formset comprised of dynamic forms, you must build the forms outside the formset, add them, and then update the management form. If any data (say from request.POST) is then passed to the form, it will try to create forms inside the formset, breaking the dynamically created form.
Code
====
To use this code:
* Copy `BaseDynamicFormSet` into your forms.py
* Create a derived class specific to your needs (`BaseQuizDynamicFormSet` in this example).
* Override `__init__`, and keep a reference to your object that you need to build your custom formset (`quiz`, in this case).
* Call the parent `__init__`
* Call your custom add forms logic
* Call the parent `_defered_init`
To write your custom add_forms logic, remember these things:
* You've got to pass any bound data to your forms, and you can find it in self.data.
* You've got to construct your own unique prefixes by doing an enumerate, as shown in the example above. This is the same way it is usually handled by the formset.
Add a `formset_factory` call, and specify your derived dynamic formset as the base formset - we now have a `QuizFormSet` class that can instantiated in our view.
The view and template code look identical to a typical formset, and all of the dynamic code is encapsulated in your custom class.
Warning
=======
This solution does not yet handle forms that work with files, use the ordering/delete features, or adding additional forms to the set via javascript. I don't think that any of these would be that hard, but don't assume that they'll just work out of the box.
Provides two template tags to use in your HTML templates:
breadcrumb and breadcrumb_url.
The first allows creating of simple url, with the text portion and url portion. Or only unlinked text (as the last item in breadcrumb trail for example).
The second, can actually take the named url with arguments! Additionally it takes a title as the first argument.
This is a templatetag file that should go into your /templatetags directory.
Just change the path of the image in the method **create_crumb** and you are good to go!
Don't forget to `{% load breadcrumbs %}` at the top of your html template!
[http://drozdyuk.blogspot.com/2009/02/dagood-django-breadcrumbs.html](http://drozdyuk.blogspot.com/2009/02/dagood-django-breadcrumbs.html)
This is the code for a template tag. Put this code in your template to render your messages:
{% for message in messages %}
{% render_user_message message %}
{% endfor %}
When you're adding a message to the user's message set, follow these rules: If you want a message to appear as an error, append "0001" to the end of it. To appear as a notice, append "0002" to it. To appear as a happy message, appear "0000" to it. If no code is present, it will default to displaying as an error. This makes use of the classes "error", "notice", and "success", so you need to define these in your CSS.
For help with custom template tags, see [the Django docs](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/)
PIL IcoImagePlugin is twelve year old and it can't handle recent Windows ICO files. Here is a function that handles all ICO versions and preserve transparency.
Usage:
# Load biggest icon from file
image = load_icon('icon.ico')
# Save third icon as PNG
load_icon('icon.ico', 2).save('icon.png')
This model is designed for my webshop. The Client-object is very 'stretch-able' by defining more fields to the client. These extra fields ares stored in the ClientConfig-object.
Be sure to create a new Client-instance first and SAVE it! Without a client.id the ClientConfig won't work.
Inspired by [Eric Florenzano's](http://www.eflorenzano.com/) post about [writing simple and very fast pure-WSGI applications](http://www.eflorenzano.com/blog/post/writing-blazing-fast-infinitely-scalable-pure-wsgi/). Using [RestView](http://www.djangosnippets.org/snippets/1071/) approach. More about it on [my blog](http://my.opera.com/kubiku/blog/2009/01/16/bare-wsgi-vs-python-frameworks-django-chapter)
Template filter to hide an email address away from any sort of email harvester type web scrapers and so keep away from spam etc.
The filter should be applied on a string which represents an email address. You can optionally give the filter a parameter which will represent the name of the resulting email href link. If no extra parameter is given the email address will be used as the href text.
{{ email|mungify:"contact me" }}
or
{{ email|mungify }}
The output is javascript which will write out the email href link in a way so as to not actually show the email address in the source code as plain text.
Also posted on [my site](http://www.tomcoote.co.uk/DjangoEmailMunger.aspx).
Snippet to convert django model into soaplib model and expose it by SOAP
This snippet use [DjangoSoapApp sniplet](http://www.djangosnippets.org/snippets/979/) to autogenerate WSDL.
I've got a bunch of `Models` that form a tree like structure. I'd like to duplicate them all changing one field to something else.
Say for example I've got a `Website` which has `Pages` and `Links` and all kinds of other `Models`. Each one of these belong to a `User` (through a foreign key relation). I could use `duplicate` to create a copy of an entire website and give it to another `User` with something like this:
class Website(Model):
owner = ForeignKey('auth.User')
...
class Link(Model):
owner = ForeignKey('auth.User')
...
class Page(Model):
owner = ForeignKey('auth.User')
...
##################################
website = Website.objects.get(pk=1)
new_owner = User.objects.get(pk=1)
duplicate(website, new_owner, 'owner')
For a in depth example of the problem see: [Duplicating Model Instances @ STO](http://stackoverflow.com/questions/437166/duplicating-model-instances-and-their-related-objects-in-django-algorithm-for-r)
*Note*
* Not tested with anything but simple Foreign Key relations - the model ordering is _very_ naive.
**Adapted from** [CountryField](http://www.djangosnippets.org/snippets/494/) - **Initial thanks to marinho**
Uses the UN country list listed in the source - this provides the 3 character ISO country code.
Ordered by display value and not country code.
Just place anywhere you like and import CountryField to use.
`country = CountryField(verbose_name="Country", help_text="The registrant's country of residence.")`
When executing custom sql, the temptation is to use fetchall or fetchone, since the API for fetchmany is a bit awkward. (fetchall makes all records resident in client memory at once; fetchone takes a network round-trip to the DB for each record.)
This snippet, hoisted from django.db.models.sql.query.results_iter, presents a nice, simple iterator over multiple fetchmany calls which hits a sweet spot of minimizing memory and network usage.