I have a Django application where I use multi-select with dynamic choices as related to the logged-in user, but when I try to submit the form, I keep getting the following error message:
"TypeError at /masstext.html Field 'id' expected a number but got <QueryDict: {'customers': [''], 'textmessage': ['test'], 'csrfmiddlewaretoken': ['FNawscd4CXqtDWIUrq0Kolq3x6R699lStaykXwxDbtqciJortBm0pTfPWSvvjW7L']}>"
I'd like to have it where, when the user submits the form, a new model instance is created with the selected customers and the message typed out as fields. I don't understand why I'm not getting a list of selected customers from the multi-select returned in the list, but rather an empty list.
Code below:
Model:
class Masstext(models.Model):
profile = models.ForeignKey(Profile, on_delete = models.CASCADE)
message = models.CharField(max_length = 500, null = True)
customers = models.CharField(max_length = 1000, null = True)
Form:
class Textform(ModelForm):
def __init__(self, user, *args, **kwargs):
super(Textform, self).__init__(*args, **kwargs)
self.fields['customers'] = forms.ModelChoiceField(
queryset = Customers.objects.filter(facility__profile__email = user))
class Meta:
model = Masstext
fields = ['customers','message']
View:
@login_required(login_url="login/") def load_customers(request, *args,
**kwargs):
msg = ''
if request.method == 'POST':
user = request.user
form = Textform(request.POST)
if form.is_valid():
form.save()
else:
msg = "Fields are not valid"
else:
form = Textform(request.user)
context = {'form': form}
return render(request,'home/masstext.html',context)
Template:
<form action="masstext.html" method="POST">
{% csrf_token %}
<!-- Form -->
<label for="customers">Select Customers:</label>
<br>
<select name="customers" style="height: 250pt" multiple>
{% for customer in form.customers %}
<option value='{{customer.id}}'{{customer}}></option>
{% endfor %}
</select>
<br><br>
<textarea name="textmessage" rows="4" cols="75" placeholder="Write the text message you'd like to send to all tenants selected above here...">{{customer.message}}</textarea>
<br><br>
<input type="submit" value="Submit">
</form>
<!-- End of Form -->