A script I wrote a little while ago to help speed up newforms-admin conversion.
From memory it works best when run from an old-forms installation, but it is still useful post-conversion. There are some features missing, but it's supposed to be a starter.
Just install this command and run:
./manange.py port2nfa > admin.py
(To install, copy the file to management/commands/port2nfa.py in an app somewhere)
This is a ModelForms-based rewrite of the create_object and update_object generic views, with a few added features. The views now accept a "form_class" argument optionally in place of the "model" argument, so you can create and tweak your own ModelForm to pass in. They also accept a "pre_save" callback that can make any additional changes to the created or updated instance (based on request.user, for instance) before it is saved to the DB.
Usage: just save the code in a file anywhere on the PythonPath and use the create_object and update_object functions as views in your urls.py.
These three classes allows you to use enumerations (choices) in more natural model-like style. You haven't to use any magic numbers to set/get field value. And if you would like to make your enumeration a full-fledged django-model, migration should be easy.
Note, that you can subclass Item to add some context-specific attributes to it, such as `get_absolute_url()` method for instance.
Examples are provided in the form of `doctest` in the second half of the snippet.
Sometimes we need divide forms in fieldsets, but this make us declare all fields in HTML template manually.
This class is to help you to do this by a easy way.
**How to use**
First, download this file as name "sectioned_form.py"
Later, turn your form inherited from the class **SectionedForm**, override method "_html_output" and declare fieldsets and fieldset_template attribute, like below:
from sectioned_form import SectionedForm
class MyForm(forms.ModelForm, SectionedForm):
fieldsets = (
(None, ('name','age','date')),
(_('Documents'), ('number','doc_id')),
)
fieldset_template = "<h2>%s</h2>"
def _html_output(self, *args, **kwargs):
return SectionedForm._html_output(self, *args, **kwargs)
Creating new field to handle checkbox validation in situations where the checkbox must be checked, as in check to agree to terms and such.
Thanks to Daniel Pope for the [suggestion](http://code.djangoproject.com/ticket/5957#comment:7) on Django Trac Ticket #[5957](http://code.djangoproject.com/ticket/5957)
A clean_<fieldname>() method in a form subclass as described [here](http://www.djangoproject.com/documentation/newforms/#custom-form-and-field-validation). Scans the field named *file* for viruses.
My version of python-clamav does not support scanning of buffers. That is why I go through the hassle of saving the file to a temporary one.
Some functions and newforms fields for validating credit card numbers, and their expiry dates.
In my project, I have all of the credit card functions in a file called creditcards.py
Just as an overview: To validate a credit card number there are a few steps:
1. Make sure the number only contains digits and spaces. `ValidateCharacters()`
2. Remove spaces so that only numbers are left. `StripToNumbers()`
3. Check that the number validates using the Luhn Checksum `ValidateLuhnChecksum()`
4. Check to see whether the number is valid for the type of card that is selected. This is annoying because you will need to look at another cleaned field before you can check this.
Sometimes the order of the fields you get from a model needs to be adjusted when displaying its modelform. If it's just a few fields you can do it in the template, but what if you want to iterate over the form?
The fields are stored in a SortedDict, so you can change the order in the __init__ of the form. A bit clunky, yes.
I had the need to add `request.user` to the `extra_fields` argument of quite a few of my view based on [create_update for newforms snippet](http://www.djangosnippets.org/snippets/635/). I could have wraped the `create_object` function in my views.py, but as the logic is always the same, it seemed like a good idea to Not Repeat Myself.
There is a sample in the code.
You can use this snippet to allow your forms to easily edit object locations.
Take care about what you should add to your templates in order to make it work.
Observation: depends on jQuery to works!
This widget works like other multiple select widgets, but it shows a drop down field for each choice user does, and aways let a blank choice at the end where the user can choose a new, etc.
Example using it:
class MyForm(forms.ModelForm):
categories = forms.Field(widget=DropDownMultiple)
def __init__(self, *args, **kwargs):
self.base_fields['categories'].widget.choices = Category.objects.values_list('id', 'name')
super(MyForm, self).__init__(*args, **kwargs)
You can add this code to a file named "field_attrs.py" in a templatetags folder inside an application.
To use it, remember to load the file with the following template tag:
{% load field_attrs %}
And for each field you want to change the widget's attr:
{{ form.phone|attr:"style=width:143px;background-color:yellow"|attr:"size=30" }}
This filter converts a XHTML-compatible shorttag `<input ... />` to a HTML4-compatible tag `<input ...>`.
Example:
`{% for field in form %}
<dt>{{ field.label_tag }}</dt>
<dd>
{{ field.errors }}
{{ field|remove_shorttag }}
</dd>
{% endfor %}`
This will produce html4-compatible output, opposed to newform's normal XHTML output.
This is a little snippet that you can use to make your Django newforms dynamic at runtime. You can define an arbitrary number of fields of the form without loosing newforms capibilites.
You can render the form dynamically be "misusing" the "help_text" attribute of the form fields (Every form field allows the definition of this attribute). This way you can search for changes in the help_text of every field and render the form accordingly.
The form itself is dynamically defined in the view.
The form state can be saved in a Django Session Variable (specifically for Linux users with a process-based Apache Server), so that you can rebuild and verify a submitted form.