1

hey Im new to django and i need help i have a form that has two fields one of them is a choicefield and the choices attribute gets its data from views but the problem is when i call the form both fields return none here is my forms.py

class AddToCardForm(forms.Form):
     quantity = forms.CharField(required=True,
                              widget=forms.TextInput(attrs={
                                  'class': 'form-control',
                                  'type': 'text',
                                  'name': 'quantity',
                                  'value': "1",
                                  'size': "2",
                                  'id': "input-quantity",
                              }))
     color = forms.ChoiceField(widget=forms.Select(attrs={
       'name': "color",
       'class': "form-control",
             }),
       required=True,)
     def __init__(self, user, *args, **kwargs):
          my_arg = kwargs.pop('choices', None)
          super(AddToCardForm, self).__init__(*args, **kwargs)
          self.fields['color'].widget.choices = my_arg

and here is my views.py

def ItemDetail(request, slug):
item = get_object_or_404(models.Item, slug=slug)
template_name = "core/test.html"
li = []
for i in item.color.all():
    tu = (i.color_name, i.get_color_name_display())
    li.append(tu)
form = forms.AddToCardForm(request.POST or None, choices=li) #
context = {
    'object': item,
    'form': form
}
if request.method == 'POST':
    print(form['color'].value())
    print(form['quantity'].value())
    if form.is_valid():
        color = form.cleaned_data.get('color')
        print(color)
        quantity = form.cleaned_data.get('quantity')
        print(quantity)
        add_to_cart_quantity(request, slug, int(quantity), color)
    else:
        print('form invalid')
        print(form.errors)
return render(request, template_name, context)

html template

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="POST">{% csrf_token %}
{{ form.as_p }}
<button type="submit">submit</button>
</form>
</body>
</html>

when i set the choices attribute in form with static data everything works fine but i need to set the choices from my model so any help would be awesome thanks

0 Answers0