Re: Working with a Custom, Dynamic Form (using BaseForm)

149 views
Skip to first unread message

Anton Baklanov

unread,
Jul 31, 2012, 3:05:41 PM7/31/12
to django...@googlegroups.com
what is going on here:
    self.base_fields = fields_for_a(self.instance) ?



On Tue, Jul 31, 2012 at 8:14 PM, Nick_B <nickb...@gmail.com> wrote:
Hi,

Have hit a huge roadblock trying to implement a custom, dynamic form into my django project. Although I am more familiar with using ModelForms, I need to use BaseForm to work with the structure I already have in place.

I have a dictionary of objects inside of my Model 'Photographer' that I am trying to pass into my form. The objects from 'Photographer' will be a drop down option for the user to select from, then will become part of an instance of another model 'A' after the user submits the form. I cannot figure out how to include the objects from 'Photographer' into my form, given the following form structure:

    class AForm(BaseForm):
        def __init__(self, data=None, files=None, instance=None, auto_id='id_%s',
                     prefix=None, initial=None, error_class=ErrorList,
                     label_suffix=':', empty_permitted=False):

            if not instance:
                raise NotImplementedError("Instance must be provided")

            self.instance = instance
            object_data = self.instance.fields_dict()
            self.declared_fields = SortedDict()
            self.base_fields = fields_for_a(self.instance)

            # if initial was provided, it should override the values from instance
            if initial is not None:
                object_data.update(initial)

            BaseForm.__init__(self, data, files, auto_id, prefix, object_data,
                              error_class, label_suffix, empty_permitted)

            cleaned_data = self.cleaned_data

            # save fieldvalues for self.instance
            fields = field_list(self.instance)

            for field in fields:
                if field.enable_wysiwyg:
                    value = unicode(strip(cleaned_data[field.name]))
                else:
                    value = unicode(cleaned_data[field.name])

            return self.instance

For a more full representation of the problem in general, including all of the models and a lot of the view code, please see my stack overflow question: http://stackoverflow.com/questions/11548992/adding-values-to-complex-django-view

I cannot thank you enough for any advice given. I have been struggling with this issue for over a month, sadly. I appreciate any commentary.


Thank you!

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/GkiNhsL225kJ.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.



--
Regards,
Anton Baklanov

Nick_B

unread,
Aug 1, 2012, 1:36:45 PM8/1/12
to django...@googlegroups.com
Hi Anton,

Thank you very much for your response. The 'fields_for_a' is generating the form fields for the instance of the model 'A'. The author admits that it might not be the prettiest implementation, but fully functional. 


def fields_for_a(instance):
    # generate a sorted dict of fields corresponding to the Field model
    # for the A instance
    fields_dict = SortedDict()
    fields = field_list(instance)
    # this really, really should be refactored
    for field in fields:
        if field.field_type == Field.BOOLEAN_FIELD:
            fields_dict[field.name] = forms.BooleanField(label=field.label, required=False, help_text=field.help_text)
        elif field.field_type == Field.CHAR_FIELD:
            widget = forms.TextInput
            fields_dict[field.name] = forms.CharField(label=field.label, required=field.required, max_length=field.max_length, help_text=field.help_text, widget=widget)

.........................(etc)................

             fields_dict[field.name] = field_type(label=field.label,
                                                 required=field.required,
                                                 help_text=field.help_text,
                                                 max_length=field.max_length,
                                                 widget=widget)

    return fields_dict


I am hoping to add an additional field, "Photographers" (from the 'Photographer' model) to AForm so that users can select a Photographer to become part of an instance of the 'A' model.

Does that make sense?


Thank you very much for any ideas!

Nick_B

unread,
Aug 1, 2012, 1:43:27 PM8/1/12
to django...@googlegroups.com
Here are my models, if you are interested:

    class Photographer(models.Model):
        name = models.CharField(max_length=20)
        models = models.ManyToManyField('Model')

    class Model(models.Model):
        model = models.CharField(max_length=20, blank=False)
        series = models.ForeignKey('Series', null=True, blank=True)

    class A(models.Model):
        user = models.ForeignKey(User)
        photographer = models.ForeignKey('Photographer', blank=True, null=True)
        model = models.ForeignKey('Model', blank=True, null=True)



Thanks folks

Anton Baklanov

unread,
Aug 4, 2012, 12:37:30 PM8/4/12
to django...@googlegroups.com


I am hoping to add an additional field, "Photographers" (from the 'Photographer' model) to AForm so that users can select a Photographer to become part of an instance of the 'A' model.

Does that make sense?

yes, you need to add field and I'm guessing that ModelChoiceField will work for you. https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoic efield

looks like you are using some additional layer before django.forms and don't just create fields directly, so you may need to extend it too.
 


Thank you very much for any ideas!

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/JMg7nHwI44sJ.

To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.



--
Regards,
Anton Baklanov

Nick_B

unread,
Aug 13, 2012, 2:57:05 PM8/13/12
to django...@googlegroups.com
Thanks for the advice Anton,


looks like you are using some additional layer before django.forms and don't just create fields directly, so you may need to extend it too.
 

Does anyone have any advice or references on extending my form to include an extra field? After searching and reading for days, I'm still lost on how to make it happen?


Thanks!
Nick_B 
Reply all
Reply to author
Forward
0 new messages