Tosin Ayoola
Tosin Ayoola

Reputation: 79

how can i save html checkbox value to django database

I'm working on a subscription project that allows user select multiple services using checkbox and then calculate the total price for these services(something like selecting multiple mails from your mail account), I have these in the HTML and Js code but I wan to be able to store each selected services to the DB, please how can I archive this

<form action="{% url 'sub:basic_starter' %}" id="subscription" method="post">
        {% csrf_token %}
          <fieldset>
            <legend><h5><strong>Business Type: </strong> New Business </h5> </legend>
             <label>Brand Value Design:                       N6,180.00
              <input type="checkbox" value=" 6179.50" name="services" id="bs1" onclick="subscribe())">
            </label><br><br>
            <label>Business Development:                     N6,180.00
              <input type="checkbox" value="6180.00" name="services" id="bs2" onclick="subscribe())">
            </label><br><br>
            <label>Website Design & Dev:              N6,180.00
              <input type="checkbox" value=" 6180.00" name="services" id="bs3" onclick="subscribe())">
            </label><br><br>
            <label>Mobile Application :          N6,180.00
              <input type="checkbox" value="6180.00" name="services" id="bs4" onclick="subscribe())">
            </label><br><br>
            <label>Maintenance(Host & Domain):             N5,450.00
              <input type="checkbox" value="5450.00" name="services" id="bs5" onclick="subscribe())">
            </label><br><br>
            <label>Social Media Management:
              <input type="checkbox" value="" name="services" id="bs6" onclick="subscribe())">
            </label><br><br>
            <input type="text" readonly="readonly" id="total" value="N0.00" ><script>document.getElementById('total').innerHTML=price;</script><br><br>
            <input type="submit" value="Subscribe" class="btn btn-success"></a></button><br>
          </fieldset>
       </form>          
    </div>  

JS

function subscribe(){
let input = document.getElementsByName('services'),
 total = 0.00,
 form = document.getElementById('subscription');
for (let i = 0; i < input.length; i++) {
    if(input[i].checked){
         total += parseFloat(input[i].value)
         let price = 'N' + total
    }    
}
document.getElementById('total').value = total.toFixed(3)

} document.getElementById('subscription').addEventListener('change', subscribe)

Views.py

@login_required
def subscribe(request):
    service_list = []
    if request.method == 'POST':
        sub_form = MembershipForm(request.POST)
        if sub_form.is_valid() and sub_form.cleaned_data:
            service_list.append(sub_form.data['service_name'])
            sub_form.save()
    else:
         sub_form =MembershipForm()
    return render(request, 'sub/subscribe_form.html',{'sub_form':  
    sub_form})

Url path('sub', views.subscribe, name='subscribe'),

Forms

class MembershipForm(forms.ModelForm):
    class Meta:
        model = Services
        fields = ('service_name', 'price',)

Models

class Services(models.Model):
    package_name = models.CharField(max_length=100)
    category = models.CharField(max_length=200)
    service_name = models.CharField(max_length=250)
    price = models.DecimalField(max_digits=9, decimal_places=2)

    def __str__(self):
        return self.service_name

    class Meta:
        unique_together = ('package_name', 'service_name')


class CompanySubscription(models.Model):
    company_name = models.ForeignKey(CompanyProfile,  
     on_delete=models.CASCADE)
    services = models.ForeignKey(Services, on_delete=models.CASCADE)
    duration = models.CharField(max_length=50)
    timestamp= models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.company_name

Upvotes: 0

Views: 5120

Answers (1)

Manan M.
Manan M.

Reputation: 1394

If you want to get all checked checkbox value, you have to write below in your view...

@login_required
def subscribe(request):
    service_list = []
    if request.method == 'POST':
        sub_form = MembershipForm(request.POST)
        if sub_form.is_valid() and sub_form.cleaned_data:

            services_price_list = request.POST.getlist('services[]')

            service_list.append(sub_form.data['service_name'])
            services_obj = sub_form.save(commit=False)
            services_obj.price = sum(services_price_list)
            services_obj.save()
    else:
         sub_form =MembershipForm()
    return render(request, 'sub/subscribe_form.html',{'sub_form':  
    sub_form})

Upvotes: 0

Related Questions