S
S
Stanislav Konovalov2019-03-25 21:23:59
JavaScript
Stanislav Konovalov, 2019-03-25 21:23:59

Django. How to hide unnecessary fields in the form depending on the selected category?

Hi everybody. I need to make it so that when adding a new ad, selecting a category hides unnecessary fields in the form. I understand that this is done through JS, but I still don’t understand well, so I ask you to tell me if anyone understands well.
For example, I want "Floor" to disappear when "Houses and Lots" is selected:
5cc6b7c5a1850755852236.png
Here is my main model:

class Listing(models.Model):
  realtor = models.ForeignKey(Realtor, on_delete=models.CASCADE, verbose_name='Риелтор')
  category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Категория')
  region = models.ForeignKey(Region, on_delete=models.CASCADE, verbose_name='Область')
  city = models.ForeignKey(City, on_delete=models.CASCADE, verbose_name='Город')
  district = models.ForeignKey(District, on_delete=models.CASCADE, verbose_name='Район')
  title = models.CharField(max_length=200, verbose_name='Заголовок')
  landmark = models.CharField(blank=True, max_length=200, verbose_name='Ориентир')
  description = models.TextField(blank=True, verbose_name='Описание')
  stage = models.IntegerField(default=0, blank=True, verbose_name='Этаж')
  rooms = models.IntegerField(default=0, blank=True, verbose_name='Количество комнат')

forms.py:
class ListingForm(forms.ModelForm):
    class Meta:
        model = Listing
        exclude = ('realtor',)

Form in template:
<form method="POST"  novalidate enctype="multipart/form-data">
   {% csrf_token %}
   {% bootstrap_form form %}
   <input type="submit" value="Добавить" class="btn btn-secondary btn-block">
</form>

I looked in the browser for the form structure in the template:
<div class="form-group">
<label for="id_category">Категория</label>
<select name="category" class="form-control" title="" required id="id_category">
  <option value="" selected>---------</option>
  <option value="1">Квартиры</option>
  <option value="2">Коммерческое</option>
  <option value="3">Дома и участки</option>
</select></div>

Structure of the field I want to hide:
<div class="form-group">
<label for="id_stage">Этаж</label>
<input type="number" name="stage" value="0" 
class="form-control" placeholder="Этаж" title="" id="id_stage">
</div>

I tried to do this, but it doesn't work yet:
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script>
    $('#id_category').change(function () {
      var optionSelected = $("option:selected", this);
      var valueSelected = $(this).val();
      
      if (valueSelected === 3){
          $('#id_rooms').hide();
      } else {
          $('#id_rooms').show();
      }
    });
  </script>

If you know, tell me, please, or an example of how this is done. Thanks in advance.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Igor, 2019-03-25
@Igorello74

Although I am a web beginner, I have a feeling that I need to dig towards the client side, namely JS. Look at the special resources for some event called upon filling out the form (see the same javascript.ru ) and make a call to the DOM in it to hide the element. If anything, you can throw a question somewhere in the JS topic, they say how to hide some other element by filling the drop-down menu. Something like this.

D
Dmitry, 2019-04-06
@pyHammer

Somehow I did something similar a very long time ago, but for the address form. I took the idea from PayPal
https://www.ushanka.com/ here on this site, add the product to the cart and go to the cart itself, then "Pay with card". But on this site it was critical only for USA, so I have a default form configured for all countries, and USA is specific.
This is done through a GET request to the view, which takes the category parameter as input (preferably the slug string parameter), then the view imports the required Form from forms.py of your application, if there is no specific class for the category, import the DefaultCategoryForm through an exception, in the same way pull up the template, you can use select_template(). Next, render this piece of the form and paste it into your HTML.
But you also need to take into account that during validation you need to substitute the desired form. It is better to assemble it on the fly using type().
On another simpler project, I used betterforms. There you need to create groups of forms, and on the class attribute, for example, hang the slug of those categories of fields that you want to display for a particular category. But this option is suitable for optional fields. That is, it cannot be used everywhere.

7
776166, 2019-04-07
@776166

There are two options: on the front and on the back.
At the front, you need to jscript. On the back, you can make a view into which, when changed, the form will be ajaxed or the entire page will be reloaded, recalculating the form and returning it back.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question