mercredi 8 janvier 2020

Cannot access value for CheckboxSelectMultiple using request.POST

I am designing a form which uses CheckboxSelectMultiple to let a user select toppings for a pizza. Topping is its own class with just a 'name' attribute.

class Pizza(models.Model):
    menu = models.ForeignKey(Menu, on_delete=models.CASCADE, related_name="pizza")
    style = models.ForeignKey(PizzaStyle, on_delete=models.CASCADE)
    size = models.ForeignKey(Size, on_delete=models.CASCADE)
    is_special = models.BooleanField(default=False)
    num_toppings = models.IntegerField()
    toppings = models.ManyToManyField(Topping, blank=True)
    price = models.DecimalField(max_digits=5, default=0.00, decimal_places=2)

class PizzaForm(ModelForm):
    class Meta:
        model = Pizza
        exclude = ['menu', 'price']
        widgets = {
            'toppings': CheckboxSelectMultiple,
        }
        labels = {
            'num_toppings': 'Number of Toppings',
            'is_special': 'Gluten Free Dough'
        }

The form creates fine in views.py with the correct labels for each Topping. However, when I pass the form data to another page (cart), I can only pass the number of the last checkbox selected in the form. (i.e. if pepperoni is selected and is the third checkbox in the list, then request.POST['toppings'] returns 3.

I'm trying to do something like this in views.py for cart such that I can generate a list of toppings:

toppings = ""
for topping in request.POST['toppings']:
     print(topping.label)
     toppings = ", ".join(topping)

I have tried some searching through the documentation but cannot seem to figure out my problem. Thank you!




Aucun commentaire:

Enregistrer un commentaire