Django AuthenticationForm and non field errors

Here’s a quick tip for the built in Django AuthenticationForm in django.contrib.auth.forms: use the non_field_errors method when trying to display the incorrect user/pass error. The error is raised in the general clean method and is not bound to any field, so using form.errors doesn’t give you the error message itself.

{{ form.non_field_errors }}

Django forms: Adding a blank option to a required choice field

Recently I came across a problem where I had a django form choicefield that needed to be required, but also needed a blank choice in case the user didn’t see the field and incorrectly submitted the first value. I saw a stack overflow post recommending to make a clean method to check that the first choice isn’t selected. That post is here:

http://stackoverflow.com/questions/5289491/blank-option-in-required-choicefield

… but a better way to do this is to simply leave the value of the blank choice as an empty string, which will invalidate the form without any extra clean method, like below:


CHOICES_WITH_BLANK = (
    ('', '--------'),
    ('1', 'choice one'),
    ('2', 'choice two'),
)

class ChoiceForm(forms.Form):
     choice_field = forms.ChoiceField(choices=CHOICES_WITH_BLANK)

Django forms: passing variables to a modelchoicefield

So I came across the problem of needing to filter my Django ModelChoiceField queryset by a variable in my view. Specifically I needed to pass the current selected state to the ModelChoiceField queryset. The best way I found to do this is to initialize the form with my state var in the initial:

state = 'OH'
form = LocationForm(initial={'state':state})

After that, instead of creating the field the traditional way, you can append the field to the self.fields dictionary within the init, enabling you to pass the initial state variable into the queryset of the field. Here is my form:

class LocationForm(forms.Form):

    def __init__(self, *args, **kwargs):
        super(LocationForm, self).__init__(*args, **kwargs)
        self.fields.insert(len(self.fields)-1, 'location',
                           forms.ModelChoiceField(queryset=Location.objects.filter(state=self.initial['state'])))

    first_name = forms.CharField(50, label="First Name")
    last_name = forms.CharField(50, label="Last Name")
    address = forms.CharField(60, label="Street Address")
    city = forms.CharField(40, label="City")
    state = USStateField()
    zip = USZipCodeField()

Self.fields is a Django SortedDict, and it’s insert method takes the index to insert to, the key, and the value.