skip to Main Content

how do i implement this in django-form?
2/3: 2 is current picked amount of item, 3 is maximum
This form does not work with the model, it will send data after clicking to the redis server
So, how can i hide form under – n/N +

enter image description here

2

Answers


  1. Here I tried to solve your requirement

    models.py

    class Demo(models.Model):
        name =models.CharField(max_length=200)
        total_img = models.IntegerField(default=0)
        photo = models.ImageField(upload_to = 'Images',blank=True,null=True)
    

    form.py

    class DemoForm(forms.ModelForm):
        class Meta:
            model = Demo
            fields = "__all__"
    

    Rendering form in Html

    {% load static %}
     <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>
            
        </title>
    </head>
    <body >
      
        <p>{{form.name.label}}{{form.name}}</p>    
        <p>
             {{form.total_img.label}}
             <a style="background-color: #ffb3b3; padding: 5px; border: 1px solid black; cursor: pointer; " onclick="dec()">-</a>
             {{form.total_img}}
             <a style="background-color: #b3ffb3; padding: 5px; border: 1px solid black; cursor: pointer;" onclick="inc()">+</a>
        </p>
        <p>{{form.photo.label}}{{form.photo}}</p>   
    
    <script>
    function inc() {
        let number = document.querySelector('[name="total_img"]');
        if  (number.value > parseInt(2)){
            alert("You can increase up to 3")
        }
        else {
            number.value = parseInt(number.value) + 1;
            console.log(number.value);
        }
    }
    
    function dec() {
        let number = document.querySelector('[name="total_img"]');
        if (parseInt(number.value) > 1) {
            number.value = parseInt(number.value) - 1;
        }
    
        else {
            alert("You can decrease up to 1")
        }
    }
        
    </script>
    </body>
    </html>
    

    Output Becomes like this

    ![enter image description here

    NOTE – Here I wrote javascript for handle + and – buttons.buttons work by targeting the name of the Number Input

    Login or Signup to reply.
  2. Consider having a look at:
    django.forms import widgets, inlineformset_factory
    This would be valuable based on your use case but it depends on how you define your code.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search