tuskar-ui/horizon/forms/base.py
Gabriel Hurley 9ac1f9b4d0 Separate "modal" behavior from "self-handling" in forms.
Splits behaviors related to a form being modal from the
requirement that the form also be self-handling by making
the component classes into mixins. This allows mixing
modal capabilities into other generic form classes.

Change-Id: Id9fb7d278e7cb48d923e2a0dd5cc6dd524a7b073
2012-08-06 13:49:40 -07:00

61 lines
2.2 KiB
Python

# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from django import forms
from django.forms.forms import NON_FIELD_ERRORS
from django.utils import dates, timezone
class SelfHandlingMixin(object):
def __init__(self, request, *args, **kwargs):
self.request = request
if not hasattr(self, "handle"):
raise NotImplementedError("%s does not define a handle method."
% self.__class__.__name__)
super(SelfHandlingMixin, self).__init__(*args, **kwargs)
class SelfHandlingForm(SelfHandlingMixin, forms.Form):
"""
A base :class:`Form <django:django.forms.Form>` class which includes
processing logic in its subclasses.
"""
def api_error(self, message):
"""
Adds an error to the form's error dictionary after validation
based on problems reported via the API. This is useful when you
wish for API errors to appear as errors on the form rather than
using the messages framework.
"""
self._errors[NON_FIELD_ERRORS] = self.error_class([message])
class DateForm(forms.Form):
""" A simple form for selecting a start date. """
month = forms.ChoiceField(choices=dates.MONTHS.items())
year = forms.ChoiceField()
def __init__(self, *args, **kwargs):
super(DateForm, self).__init__(*args, **kwargs)
years = [(year, year) for year
in xrange(2009, timezone.now().year + 1)]
years.reverse()
self.fields['year'].choices = years