Sample jQuery javascript to use this view:
$(function(){
$("#id_username, #id_password, #id_password2, #id_email").blur(function(){
var url = "/ajax/validate-registration-form/?field=" + this.name;
var field = this.name;
$.ajax({
url: url, data: $("#registration_form").serialize(),
type: "post", dataType: "json",
success: function (response){
if(response.valid)
{
$("#"+field+"_errors").html("Sounds good");
}
else
{
$("#"+field+"_errors").html(response.errors);
}
}
});
});
});
For each field you will have to put a div/span with id like fieldname_errors where the error message will be shown.
You can place this code above your form and it will list out all errors in your form if there are errors. Sometimes I like listing the errors at the top of the form because I think it looks cleaner. Make sure you add error_messages={'required': 'My detailed error here'} in your view.py for your form.
This security field is based on the perception that spambots post data to forms in very short or very long regular intervals of time, where it takes reasonable time to fill in a form and to submit it for human beings.
Instead of captcha images or Ajax-based security interaction, the SecurityField checks the time of rendering the form, and the time when it was submitted. If the interval is within the specific range (for example, from 5 seconds till 1 hour), then the submitter is considered as a human being. Otherwise the form doesn't validate.
Usage example:
class TestForm(forms.Form):
prevent_spam = SecurityField()
# ... other fields ...
The concept works only for unbounded forms.
This a wizard tool similar to the one in django.contrib.formtools, but it uses a session. I hope to eventually get this into shape and contribute it to the formtools package, but for right now, here it is.
The wizard steps are broken into 2 categories:
Show Form and Submit Form
Each category has it's own hooks for manipulating the process, for instance you can short-circuit a process_submit_form() and go straight to done() via a return from preprocess_submit_form(). Sorry for the lack of documentation on this.
Here's an example urls.py entry :
`(r'^estimate/(?P<page0>\d+)/$', EstimateWizard([EstimateCustomer, EstimateJob, EstimateRoom]))`
where EstimateCustomer, Job, and Room are Form classes and EstimateWizard extends SessionFormWizard
Take the legwork out of processing forms.
Most people have a very specific structure to how they process forms in views. If the request method is "GET", then some HTML (with the blank form) is rendered. If the method is "POST", then the form is validated. If the form is invalid, some other HTML is displayed. If valid, the data is submitted and processed in some way.
In order to do this all in a much nicer way, simply subclass `FormHandler`, define three methods (`valid`, `invalid` and `unbound`), point to the form, and use the subclass as your view in the URLconf.
I recently got a form working via jQuery and Django. This was not easy for me to do and I thought I'd record my finding here.
The form submits via jQuery and the "form" plugin. Please visit jQuery's home page to find all those links.
This code handles:
* urls.py -- passing both normal and 'Ajax' urls to a view.
* views.py -- Handling both kinds of requests so that both normal and ajax submits will work.
* The HTML template with the script for submitting and some bling.
Error handling
===
I like to stay DRY so the idea of checking the form for errors in javascript *and* checking it in Django irks me. I decided to leave that up to Django, so the form submits and gets validated on the server. The error messages are sent back to the browser and then displayed.
DualPasswordForm is a simple form that contains two password fields and validation to ensure that the two passwords match. A minimum password length of 7 characters is imposed, but feel free to change that.
Simple DecimalField class extension that automatically adds formatting and validation for comma-separated "decimals". Works wonderfully for price fields.
Could be extended to strip dollar signs or to be locale-agnostic.
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)
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 template tag build a Form splitted in fieldsets. The fieldsets are configured with a second parameter, that is a tuple like the one used in the Admin class in models in the attribute "fields".
You pass to the template the form and the tuple and than use them as parameters for the templatetag.
You can take a look at the source and modify It to build forms the way you like.
It is very useful If you do not like the way Django build forms with the methods as_p, as_ul or as_table and also do not like to write html by hand.
**This is a newforms field for XFN relationships.**
It normalizes input by removing excess whitespace, converting to lowercase and removing duplicates.
This field also validates the relationship according to the [XFN profile](http://gmpg.org/xfn/11): `me` can only appear by itself and, at most, one value from each of the family, friendship and geographical categories is allowed.
The `XFN_*` constants would probably be imported from somewhere else in practice, but are included here for simplicity.
**This is a newforms field for OpenID 1 & 2.**
It normalizes and validates OpenID identifiers according to the [spec](http://openid.net/specs/openid-authentication-2_0.html#normalization):
* `xri://=joelwatts` to `=joelwatts`
* `joelwatts.com` to `http://joelwatts.com/`
* `www.joelwatts.com` to `http://joelwatts.com/`
An identifier that is well-formed, but not an OpenID (e.g. `example.com`), will cause a validation error.
Requires [Python OpenID Library](http://openidenabled.com/python-openid/) 2.x.x.
Generator to help make newforms classes a bit like inspectdb does for generating rough model code. This is a standalone script to go in your project directory with settings.py and called from the prompt. It looks up the model, and generates code to copy/paste into your app. Hopefully to make a building a custom form with a lot of fields a little easier. Every argument should be a model identifier of form appname.modelname.
Usage from the command line:
python form_gen myapp.MyModel myapp.MyOtherModel