I Want To Save The Data In My Database Depending On The Catgory Of Data Chosen by User Like I Have 4 Lisiting

I Want To Save The Data In My Database Depending On The Catgory Of Data Chosen by User Like I Have 4 Lisitings Like APparetements, Food And Life, Car And Travelling if User Selects Appartements Then Area, location Fields Are Showed An getiing Data And Saved Data Else Hidden and Disabled For Other Fields Like Food And Life, Car And Travellig. MY COde Of MyListing.html

{% extends 'home.html' %}
{% load static %}
{% block content %}

<div class="page-heading">
    <div class="container">
      <div class="row">
        <div class="col-lg-8">
          <div class="top-text header-text">
            <h6>Add Plots In Your Listing</h6>
            <h2>If You Want To Buy The Plot Then Add It In Your Listing</h2>
          </div>
        </div>
      </div>
    </div>
</div>

<div class="contact-page">
    <div class="container">
      <div class="row">
        <div class="col-lg-12">
          <div class="inner-content">
            <div class="row">
              
              <div class="col-lg-6 align-self-center">
                <form id="contact" action="" method="POST" enctype="multipart/form-data">
                  <div class="row">
                    {% csrf_token %}
                    <div class="col-lg-12">
                        <label for="">Listing Type</label>
                        {{ form.listing_type }}
                            <label for="" >Area</label>
                            {{ form.area }}
                            <label for="">Location</label>
                            {{ form.location }}

                            <label for="">Price</label>
                            {{ form.price }}
                            <label for="">Title</label>
                            {{ form.title }}
                            <label for="">Upload An Image</label>
                            {{ form.image }}
                    </div>
                    
                    <div class="col-lg-12">
                      <fieldset>
                        <button type="submit" id="form-submit" class="main-button "><i class="fa fa-paper-plane"></i>Add Your Listing!</button>
                      </fieldset>
                    </div>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function() {
        var categorySelect = $('#id_listing_type'); // Corrected selector
        var areaField = $('#id_area');
        var locationField = $('#id_location'); // Define locationField
    
        areaField.prop('disabled', true); // Disable the field initially
        locationField.prop('disabled', true);
    
        categorySelect.on('change', function() {
            var selectedCategory = $(this).val();
    
            if (selectedCategory === 'appartements') {
                areaField.prop('disabled', false); // Enable the field
                locationField.prop('disabled', false);
            } else {
                areaField.prop('disabled', true); // Disable the field
                locationField.prop('disabled', true);
            }
        });
    });
    </script>
    
    
    
    
    
    

{% endblock content %}
class My_listings(FormView):
    template_name = 'Mylisting.html'
    form_class = Mylisting_form
    success_url = '/contact/'

    def form_valid(self, form):
        form.save()
        return super().form_valid(form)```

You didn’t describe the problem you encounter, so it’s not easy to provide any help.

Also, the issue is related to saving things to database, so the most important parts are the model and the form that is supposed to do the saving (through form.save()), but you provided none of the model nor the form implementation.

1 Like

Code Of my FOrms

class Mylisting_form(forms.ModelForm):
    class Meta:
        model = Listing
        fields = ['area', 'location', 'price', 'image', 'title', 'listing_type']
        widgets = {
            'area': forms.TextInput(attrs={'class': 'form-control'}),
            'location': forms.TextInput(attrs={'class': 'form-control'}),
            'price': forms.TextInput(attrs={'class': 'form-control'}),
            'title': forms.TextInput(attrs={'class': 'form-control'}),
            'listing_type': forms.Select(attrs={'class': 'form-control'}),
        }
        
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Disable area and location fields by default
        self.fields['area'].widget.attrs['disabled'] = True
        self.fields['location'].widget.attrs['disabled'] = True
    
    def clean(self):
        cleaned_data = super().clean()
        listing_type = cleaned_data.get('listing_type')

        if listing_type in ['Apartments', 'Traveling', 'Car']:
            self.fields['area'].widget.attrs['disabled'] = False
            self.fields['location'].widget.attrs['disabled'] = False
        else:
            self.fields['area'].widget.attrs['disabled'] = True
            self.fields['location'].widget.attrs['disabled'] = True

        return cleaned_data

Code Of My Models

class Listing(models.Model):
    TYPE_CHOICES = [
        ('Car', 'Car'),
        ('Food and Life', 'Food and Life'),
        ('Travelling', 'Travelling'),
        ('Appartements', 'Appartements'),
    ]
    
    area = models.CharField(max_length=80)
    location = models.CharField(max_length=80)
    price = models.IntegerField()
    image = models.ImageField(upload_to='shop/images', default="")
    title = models.CharField(max_length=170, default="")
    listing_type = models.CharField(max_length=20, choices=TYPE_CHOICES)

That looks pretty good, except area and location fields on the model that should probably have a blank=True parameter.

What is the problem you encounter?

it Disable Area And Location Field For All Listing Type

Your javascript is incorrect:

Area and location fields are enabled only for the appartements category which is not a valid choice. Correct value is Appartements (with a capital letter)

Also, the test done in clean method is inconsistent with your javascript, and tested values does not correspond to valid choices.

However, disabling widgets in the clean method is useless, as widgets are not used at validation time