예제 #1
0
    def __init__(self, *args, **kwargs):
        super(RelatedFormBoundFieldBase, self).__init__(*args, **kwargs)
        self.passing_kwargs = getattr(self.field, 'passing_kwargs', {})
        self.form_class = getattr(self.field, 'form_class', None)

        # curry the widget creation with our ``get_form`` method. 
        self.widget = RelatedFormWidget(self.get_form) 

        if self.form_class is None:
            raise forms.ValidationError('``%s.%s.form_class`` is not defined' % (type(self.form), self.name))
예제 #2
0
class RelatedFormBoundFieldBase(object):
    """
        The RelatedFormBoundFieldBase object is the repository of knowledge
        for the ``form_class`` -- due to the way Django's form library works,
        the BoundField is pretty much perfectly positioned to be able to see into
        not only the form's member's, but also the incoming data as well as the original
        **kwargs going into the Field object.
    """
    def __init__(self, *args, **kwargs):
        super(RelatedFormBoundFieldBase, self).__init__(*args, **kwargs)
        self.passing_kwargs = getattr(self.field, 'passing_kwargs', {})
        self.form_class = getattr(self.field, 'form_class', None)

        # curry the widget creation with our ``get_form`` method. 
        self.widget = RelatedFormWidget(self.get_form) 

        if self.form_class is None:
            raise forms.ValidationError('``%s.%s.form_class`` is not defined' % (type(self.form), self.name))

    def as_widget(self, widget=None, *args, **kwargs):
        # Override the default ``as_widget`` bits so we can use our super-special
        # form-widget.
        if widget is None:
            widget = self.widget
        return super(RelatedFormBoundFieldBase, self).as_widget(widget, *args, **kwargs)

    def value(self):
        return self.widget.value_from_datadict(self.form.data or self.form.initial, self.form.files, self.form.add_prefix(self.name))

    def get_form(self, *args, **kwargs):
        updated_kwargs = {}
        for key, value in self.passing_kwargs.iteritems():
            call_function = getattr(self.form, value)
            if callable(call_function):
                # if it's a callable, call it!
                updated_kwargs[key] = callable(call_function)
            else:
                # otherwise just grab the attribute and move on.
                updated_kwargs[key] = call_function

        base_kwargs = {}
        base_kwargs.update(kwargs)
        base_kwargs.update(updated_kwargs)

        return self.form_class(*args, **base_kwargs)