Django access to related model fields in form view
I'm trying to create a form that retrieves all objects for one table (students) in the database and let the user select which one of them they want to pick to send an email.
Right now I'm not able to properly render the students data, but it is actually showing the right number of students. If I pick the second input the one render by student.tag
it actually retrieves the right information but if I pick the first one there is no information submitted.
Here is my form:
class SendEmailStudentsForm(forms.Form):
students = forms.ModelMultipleChoiceField(
queryset=Students.objects.all(),
widget=forms.CheckboxSelectMultiple,
required=False)
And the template I'm using:
<form action="#" method="post">
{% csrf_token %}
{% for student in form.students %}
<ul>
<li>{{ forloop.counter }} - {{ student.id }}</li>
<li>Email: - {{ student.email }}</li>
<li>Add student<input type="checkbox" id="{{ student.id }}"></li>
<li>Add <span>{{ student.tag }}</span></li>
</ul>
{% endfor %}
<button type="submit" class="btn btn-primary">Send emails</button>
<a href="{% url 'students:index' %}" class="btn btn-primary">Back</a>
</form>
And my view:
def select_students_emails(request):
if request.method == "POST":
form = SendEmailStudentsForm(request.POST)
if form.is_valid():
print(form.cleaned_data)
# send_mail(...)
return HttpResponseRedirect(reverse('students:index'))
else:
form = SendEmailStudentsForm()
return render(request, 'students/select_students.html', context={'form': form})