1# Copyright 2012 United States Government as represented by the 2# Administrator of the National Aeronautics and Space Administration. 3# All Rights Reserved. 4# 5# Copyright 2012 Nebula, Inc. 6# 7# Licensed under the Apache License, Version 2.0 (the "License"); you may 8# not use this file except in compliance with the License. You may obtain 9# a copy of the License at 10# 11# http://www.apache.org/licenses/LICENSE-2.0 12# 13# Unless required by applicable law or agreed to in writing, software 14# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16# License for the specific language governing permissions and limitations 17# under the License. 18 19from django import forms 20from django.forms.forms import NON_FIELD_ERRORS 21 22 23class SelfHandlingMixin(object): 24 def __init__(self, request, *args, **kwargs): 25 self.request = request 26 if not hasattr(self, "handle"): 27 raise NotImplementedError("%s does not define a handle method." 28 % self.__class__.__name__) 29 super().__init__(*args, **kwargs) 30 31 32class SelfHandlingForm(SelfHandlingMixin, forms.Form): 33 """A base Form class which includes processing logic in its subclasses.""" 34 required_css_class = 'required' 35 36 def api_error(self, message): 37 """Adds an error to the form's error dictionary. 38 39 It can be used after validation based on problems reported via the API. 40 This is useful when you wish for API errors to appear as errors on the 41 form rather than using the messages framework. 42 """ 43 self.add_error(NON_FIELD_ERRORS, message) 44 45 def set_warning(self, message): 46 """Sets a warning on the form. 47 48 Unlike NON_FIELD_ERRORS, this doesn't fail form validation. 49 """ 50 self.warnings = self.error_class([message]) 51 52 53class DateForm(forms.Form): 54 """A simple form for selecting a range of time.""" 55 start = forms.DateField(input_formats=("%Y-%m-%d",)) 56 end = forms.DateField(input_formats=("%Y-%m-%d",)) 57 58 def __init__(self, *args, **kwargs): 59 super().__init__(*args, **kwargs) 60 self.fields['start'].widget.attrs['data-date-format'] = "yyyy-mm-dd" 61 self.fields['end'].widget.attrs['data-date-format'] = "yyyy-mm-dd" 62