Django form does not show specific input

Say I have 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 the 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 can I hide the fields in the form if the user does not have available “ships” (ie = 0 in the Fleet model)?

+4
source share
2 answers

You can override visible_fields (or hidden_fields if you really want a hidden field) methods in your form to designate them as “invisible” (or hidden inputs). See docs for more 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 %} 
+2
source

It seems that this problem is better solved using ManyToManyField from Fleet to Ship or ForeignKey from ship to form, and then just ModelMultipleChoiceField in your form ... but maybe there is something I don’t understand.

In any case, MultipleChoiceField is probably better than this IntegerFields set. This is basically what it is for MultipleChoiceField.

+1
source

Source: https://habr.com/ru/post/1316612/


All Articles