I have a model form in my project that has a field that is swapped out
for another field based on user preferences. Some users want a select
the value from a dropdown box, other people want to just type the
value into a textbox.

Before I had it like this:

def proper_flight_form(profile):
    """
    Prepares the popup flight form based on how the user wants each
field
    widget to be rendered as.
    """

    from plane.models import Plane
    from logbook.forms import TextPlaneField, FlightForm

    if profile.text_plane:
        text_plane_field =
TextPlaneField(queryset=Plane.objects.none())
        FlightForm.base_fields['plane'] = text_plane_field
        return FlightForm

    return PopupFlightForm

This was bad because when it edited the class like that, it effected
all users. The next request that came in had the incorrect form field.
I kept getting errors such as "ValueError: invalid literal for int()
with base 10: 'N488AF'", which is caused by the form rendering the
textbox, but when it comes time to recieve that data the form class
has changed in that it now expects the data to be an integer from a
dropdown box.

So then I changed the way it worked by just defining two different
form classes, one with the textbox field, the other with the dropdown
box. This worked 100% fine, but wasn't very flexible.

So then I edited it so it deepcopies the form class first, and then
edits the fields on that copied class. I thought this would work, but
we're back to square one.

This is what I have now:

def proper_flight_form(profile):
    """
    Prepares the popup flight form based on how the user wants each
field
    widget to be rendered as.
    """

    from copy import deepcopy
    from plane.models import Plane
    from logbook.forms import TextPlaneField, FlightForm

    if profile.text_plane:
        text_plane_field =
TextPlaneField(queryset=Plane.objects.none())
        NewForm = deepcopy(FlightForm)
        NewForm.base_fields['plane'] = text_plane_field
        return NewForm

    return FlightForm

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to