N
N
nurzhannogerbek2017-05-02 20:51:54
Django
nurzhannogerbek, 2017-05-02 20:51:54

How to leave a check mark in the checkbox?

Hello! Please help me figure it out.
There is a Product data model with the is_visible field of the BooleanField data type. I want to display a form with checkboxes, by clicking on which the user would change the value of the visible field. In other words, would make the product visible or not visible.
Form example:
2f89ef431c8e4885b68cfcaf42b84930.PNG
What you have done so far you can see below. This code should, in theory, display all objects (that is, a list of all products) in the form. The user selects products by checking the checkboxes, then in views I change the values ​​of the is_visable fields to True for those products that the user has checked, but how to leave a checkmark in the checkbox for those products that have is_visable=True?
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()

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question