A simple way to handle file validation by checking for a proper content_type and by making sure that the file does not go over its limit upload size limit.
In the example I am checking to make sure the file is an image or a video file then I check to make sure that the file is below the max upload limit. if conditions are not met, then a validation error is raised
**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.")`
A simple way to log in and log out users. It's most likely nowhere near as good as the built-in login forms. This was more of a learning experience for me. Nevertheless, the script works.
Usage:
def some_view(request):
check_login(request)
Some explanation can be found here: http://bit.ly/ete0
Often I want fields in my models to be unique - Django's `unique` works too late in model form validation and will throw an exception unless you check for it by hand. This is a bit of code that cleans up the boiler plate of checking if different fields are unique.
Set `exclude_initial` to `False` if you want to raise an error if the unique field cannot be set to whatever value the instance had before.
**Update**
Thanks fnl for rightly pointing out that Django's `unique=True` does check for this - just make sure to pass `instance=obj` when you're initializing your forms. _HOWEVER_ a problem you'll typically run into with this is though you want a field to unique, you also want multiple entries to be able to be `blank`. This can help you!
This class extends MultiWidget to create a widget that consists of HTML select elements for Django's forms.DateTimeFields. This results in a select elements with options for month, day, year, hour, minute, second, and (if using the twelve_hr option) meridiem.
# Default usage of SplitSelectDateTimeWidget
class TimeForm(Form):
dt = DateTimeField(widget=SplitSelectDateTimeWidget())
Another example hooks into the flexibility of the underlying Select Widgets:
class TimeForm(Form)
dt = DateTimeField(widget=SplitSelectDateTimeWidget(hour_step=2, \
minute_step=15, second_step=30, twelve_hr=True, years=[2008,2009,2010]))
The above example displays hours in increments of 2, minutes in increments of 15, and seconds in increments of 30. Likewise, only the years 2008, 2009,and 2010 are displayed in the years' options.
This snippet defines a Widget that is very similar to the **SelectDateWidget** located in django.forms.extras.widgets. The main difference however is that it works with Times instead of Dates.
The SelectTimeWidget supports both 24-hr and 12-hr formats, and flexible time increments for hours, minutes and seconds. Sample usage is illustrated below:
# Specify a basic 24-hr time Widget (the default)
t = forms.TimeField(widget=SelectTimeWidget())
# Force minutes and seconds to be displayed in increments of 10
t = forms.TimeField(widget=SelectTimeWidget(minute_step=10, second_step=10))
# Use a 12-hr time format, which will display a 4th select
# element containing a.m. and p.m. options)
t = forms.TimeField(widget=SelectTimeWidget(twelve_hr=True))
This form widget allows you to just display data in a rendered form, not giving the user the opportunity to change it. The initial data will just be carried through the form and showed to the user.
In combination with snipped [1184](http://www.djangosnippets.org/snippets/1184/) you can make this even tamper safe. ;-)
A rewrite of the django.contrib.formtools.FormWizard class to be session-based instead of saving state in hidden form variables.
It started out as a simple port of the standard FormWizard class, and much of the original behavior was unchanged because I wanted to limit the scope of the "rewrite". Along the way I think I made it a bit more OO, and a bit more flexible, but there are still warts.
I threw this code up here before I was completely happy with it just to take part in the discussion around [this ticket][http://code.djangoproject.com/ticket/9200 "Django Ticket #9200]. There's certainly a few things that the patch on that ticket does that I'd like to incorporate into my Wizard, whenever time allows.
These field and widget are util for to those fields where you can put a star and end values.
It supports most of field types and widgets (tested with IntegerField, CharField and DateField / TextInput and a customized DateInput).
**Example of use:**
class FormSearch(forms.Form):
q = forms.CharField(max_length=50, label=_('Search for'))
price_range = RangeField(forms.IntegerField, required=False)
**Example of use (with forced widget):**
class FormSearch(forms.Form):
q = forms.CharField(max_length=50, label=_('Search for'))
price_range = RangeField(forms.IntegerField, widget=MyWidget)
A form with built-in CSRF protection. Include CsrfCookieMiddleware in your MIDDLEWARE_SETTINGS, subclass SafeForm and off you go. See:
[this django-developers post](http://groups.google.com/group/django-developers/browse_thread/thread/2c33621003992d07?hl=en) for more info.
[edit]
This form is actually WAY overengineered currently. Will update soon.
This form subclass helps protect against cross-site request forgery by adding a hidden field named `csrf_token` to forms. The form must be initialized with the request as a keyword argument, both with and without POST data:
my_form = MySignedForm(request=request)
...
my_form = MySignedForm(request.POST, request=request)
Upon validation, a `PermissionDenied` exception will be raised if forgery is detected.
If any security details have been overlooked in this recipe, please leave a comment.
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.
Here's a snippet to pair an arbitrary form Field type (the "target field") with a checkbox. If the checkbox is not selected, the cleaned_data value for the field will be None. If the checkbox is selected, it will return the target field's cleaned value.
This function emulates the file upload behaviour of django's admin, but can be used in any view. It takes a list of POST keys that represent uploaded files, and saves the files into a date-formatted directory in the same manner as a `FileField`'s `upload_to` argument.