Fahima Nizam Nova
Fahima Nizam Nova

Reputation: 13

How to make multiple choice field from Django many to many related model

I want to show products from product model using check boxes in my store form where user can select multiple products.

Product Model:

class Product(models.Model):
    product_name = models.CharField(max_length=30)
    product_price = models.IntegerField(default=0)
    timestamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.product_name

Store Model:

class Store(models.Model):
    AREAS = [
        (0, 'Dhaka'),
        (1, 'Khulna'),
        (2, 'Chittagong'),
        (3, 'Barisal'),
        (4, 'Rajshahi'),
    ]

    SELLER_TYPE = [
        (0, 'Manufacturer'),
        (1, 'Authorised Dealer'),
        (2, 'Distrubutor'),
        (3, 'Dealer'),
    ]
    
    store_owner = models.ForeignKey(User, on_delete=models.CASCADE,related_name='store_owner')
    store_name = models.CharField(max_length=256)
    store_address = models.CharField(max_length=300)
    seller_type = models.IntegerField(choices=SELLER_TYPE, default=0)
    area = models.IntegerField(choices=AREAS, default=0)
    products = models.ManyToManyField(Product, related_name='store_products')
    timestemp = models.DateTimeField(auto_now_add=True)
    updated_on = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.store_name

Store Form:

class StoreForm(forms.ModelForm):
    area = forms.ChoiceField(choices=Store.AREAS, label='Area', required=True)
    products = forms.MultipleChoiceField(queryset=Product.objects.all(), label='Manager', required=True)
    seller_type = forms.ChoiceField(widget=forms.RadioSelect, choices=Store.SELLER_TYPE)
    class Meta:
        model = Store
        fields = ('seller_type',
        'store_name', 
        'store_address', 
        'products',
        'area')

I want to select multiple product item while I'm going to create a record for a store. Currently I can select multiple product items from the product list. But I want to represent them as check-boxes so that users can select multiple items from the check-boxes.

Upvotes: 1

Views: 8156

Answers (1)

ShiBil PK
ShiBil PK

Reputation: 608

After we passing product object to template.we can call the object in template like this:

{% for product in products.all %}
  <label  for="ts1">{{product}}</label>
  <input type="checkbox" name="products" value="{{ product.pk }}" />
{% endfor %}

in view.py:

  data = form.save(commit=False)
  data.save()

  products = request.POST.getlist('products')
  for product in products:
     if Product.objects.filter(id=product).exists():
        product = Product.objects.get(id=product)
        data.products.add(product)

Upvotes: 2

Related Questions