How can I make the field layout of a model form dynamic?

25 views
Skip to first unread message

DJ-Tom

unread,
Oct 22, 2014, 7:48:14 AM10/22/14
to django...@googlegroups.com
Hi,

I have a model that contains either a text or a numerical information, based on the type of the entry:

equipment = models.ForeignKey(equipment)
number = models.DecimalField('Amount/number', max_digits=6, decimal_places=2, blank=True, null=False, default=0)
text = models.TextField("Text", blank=True, null=True, default='')

Based on that model I created a model form:

class RoomsetupEquipmentForm(ModelForm):
    equipment = forms.ModelChoiceField(queryset=equipment.activeobjects.order_by('category__name', 'name'))

    def __init__(self, *args, **kwargs):
        super(RoomsetupEquipmentForm, self).__init__(*args, **kwargs)
        self.fields['equipment'].choices = equipment_as_choices()

    class Meta:
        model = roomsetup_equipments
        fields = ('equipment', 'number', 'text')

I'm looking for a way to selectively show either the number or the text field when the form is created.

Thomas


Bill Freeman

unread,
Oct 22, 2014, 6:31:27 PM10/22/14
to django-users
Perhaps the most djangoish way would be to create two model forms, with different fields excluded, and choose which to render in the template.

Or you could render CSS style information to hide one or the other.

Or you could use JavaScript to hide one or the other based on something else that you render.

Or write the template code to render the fields instead of using .as_p, etc.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/138b45bd-ad73-4d5b-ac7f-27530b8e4e0c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages