Adding items to the cart

In order to add items to the cart, we need a form that allows the user to select a quantity. Create a forms.py file inside the cart application directory and add the following code to it:

from django import formsPRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)]class CartAddProductForm(forms.Form):    quantity = forms.TypedChoiceField(                                choices=PRODUCT_QUANTITY_CHOICES,                                coerce=int)    update = forms.BooleanField(required=False,                                initial=False,                                widget=forms.HiddenInput)

We will use this form to add products to the cart. Our CartAddProductForm class contains the following two fields:

  • quantity: This allows the user to select a quantity between 1-20. We use a TypedChoiceField field with coerce=int to convert the ...

Get Django 2 by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.