1👍
I’m not sure what you’re doing with the student_name
variable you’ve declared in the view, but you would need to do the same query in the form if you intend to show the same choices, or you need to pass some additional information to your form.
I would do:
from django import forms
class SelectorForm(forms.Form):
def __init__(*self, *args, **kwargs):
student_choices = kwargs.pop('student_choices')
super(SelectorForm, self).__init__(*args, **kwargs)
self.fields['student'] = forms.MultipleChoiceField(
widget=forms.Select({'class': 'form-control'}),
choices=student_choices
)
this way you can get the student_choices
once in the view, and just pass them to the form:
def student_view(request):
students = Student.objects.filter(user_id=request.user.id).values_list(
'name', flat=True)
student_form = StudentForm(request.POST or None, student_choices=students)
if request.method == 'POST' and student_form.is_valid():
student_name = student_form.cleaned_data.get('student')
redirect(reverse('success'))
return render(request, 'your-template.html',
{'students': students, 'student_form': student_form})
On a small side note, you really need to be using proper casing on your Python classes, which should always be title cased. Otherwise, you’ll have a hard time distinguishing between instances and definitions or the class not to mention function names, variables, etc.
Source:stackexchange.com