I have two model:
class items(models.Model):
type = models.CharField()
model = models.CharField()
class cart(models.Model):
client = models.ForeignKey(client, on_delete=models.CASCADE)
type = models.CharField()
What I want to do is to create a form that show all the items' type not already into the cart for a client. I need a multiple checkbox (and possibly an header checkbox for "select all")
I made this form manually but there is a way to make it using django form?
I tried with this code but I'm not sure that this is the best solution. How can I add a "select all" checkbox?
form.py
class AddItemsForm(Form):
def __init__(self, *args, **kwargs):
self.client_id = kwargs.pop('client_id')
super(AddItemsForm, self).__init__(*args, **kwargs)
pl = items.objects.raw("SELECT * FROM app_items WHERE type NOT IN (SELECT type FROM app_cart WHERE client_id = %s)" % self.client_id)
b = []
for p in pl:
b.append([p.type, p.type])
self.fields["choices"] = MultipleChoiceField(
choices = b,
widget = CheckboxSelectMultiple,
)
self.fields['choices'].label = ''
view.py:
def pricelist_addcountries_form(request, client_id):
if request.method == 'POST':
form = AddItemsForm(request.POST)
if form.is_valid():
...
return redirect(reverse('app:index'))
else:
form = AddItemsForm(client_id=client_id)
return render(request, 'app/form.html', {'form': form})
thanks in advance!
Aucun commentaire:
Enregistrer un commentaire