views:

27

answers:

2

Say, I've got a model like this:

class Fleet(models.Model):
    user = models.ForeignKey(User)
    [...]
    ship1 = models.IntegerField(default=0)
    ship2 = models.IntegerField(default=0)
    ship3 = models.IntegerField(default=0)
    ship4 = models.IntegerField(default=0)

And a form:

class sendFleet(forms.Form):
    [...]
    ship1 = forms.IntegerField(initial=0)
    ship2 = forms.IntegerField(initial=0)
    ship3 = forms.IntegerField(initial=0)
    ship4 = forms.IntegerField(initial=0)

How I can make the fields in the form hidden if the user has no 'ships' available (i.e = 0 in the Fleet model)?

+2  A: 

You can override the visible_fields (or hidden_fields if you really want a hidden field) methods in your form to flag them as "invisible" (or hidden inputs). See the docs for details.

EDIT: Something like this should work ...

class sendFleet(forms.Form):
    [...]
    ship1 = forms.IntegerField(initial=0)
    ship2 = forms.IntegerField(initial=0)

    def visible_fields(self):
        # create a list of fields you don't want to display
        invisibles = []
        if self.instance.ship1 == 0:
            invisibles.append(self.fields['ship1'])

        # remove fields from the list of visible fields
        visibles = super(MailForm, self).visible_fields()
        return [v for v in visibles if v.field not in invisibles]

Then in your template:

{% for field in form.visible_fields %}
    {{ field.label_tag }} : {{ field }}
{% endfor %}
ars
May I ask for an example? :-)
Robus
Sure. :) See update.
ars
+1  A: 

It seems like this problem would be better solved by using a ManyToManyField from Fleet to Ship, or a ForeignKey from Ship to Form, and then simply a ModelMultipleChoiceField in your form... but maybe there's something I'm not understanding.

Either way, a MultipleChoiceField would probably better than this set of IntegerFields. This is basically what a MultipleChoiceField is for.

Gabriel Hurley