0

Can someone say, how create such form as in the picture below in Django?

enter image description here

I have model Product with field is_visable. In form I want to show all products with field is_visable. User can select checkboxes and change the value of is_visable field. In other words make products visable or invisable. I am thing about MultipleChoiceField in my form but not sure is it correct in my case.

models.py:

class Product(models.Model):
    symbol = models.CharField(_('Symbol'), max_length=250)
    name = models.CharField(_('Name'), max_length=250)
    is_visible = models.BooleanField(default=False)

forms.py:

class ProductForm(forms.ModelForm):
    product = forms.ModelChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Product.objects.all())

views.py:

if request.method == 'POST':
    form = ProductForm(data=request.POST)
    if form.is_valid():
        ids = form.cleaned_data.get('product')  # Example: ['pk', 'pk']
        for id in ids:
            product = Product.objects.get(pk=id)
            product.is_visible = True
            product.save()
Nurzhan Nogerbek
  • 4,806
  • 16
  • 87
  • 193

1 Answers1

0

I think what you want to use is a ModelChoiceField in your form with a widget of CheckboxSelectMultiple.

A queryset for the ModelChoiceField is a required argument, so you can build the queryset like this:

visible_products =  Product.objects.filter(is_visible=True)
product_field = forms.ModelChoiceField(queryset=visible_products,
                                 widget=CheckboxSelectMultiple()

See this post for more details:

Django ChoiceField populated from database values

Community
  • 1
  • 1
rjd
  • 31
  • 1
  • Hello! Can you check my post again pls. I add form and view code. I show all products in form, then change is_visable value of products which was clicked by user in views. But I steal dont understand how to save mark in checkbox in that products which has 'is_visable=True'? Do you have any ideas about that? – Nurzhan Nogerbek May 03 '17 at 06:05