Using a Select filter to narrow choices for a form.

I’m still not clear on how the code you’ve posted fits with the description. Your AddStudentForm2 has a course field, but doesn’t show a school field. Where is the school selected here?

Also, you mention going to a new page for selecting the course, but you have this course field in this current page.

Ignoring these details for now, when you’re looking to create a new page based on information posted in the current page, you need to pass the information along to the new page to allow it to be created properly.

This is typically done in the redirect by passing that data through the url to the new view.

So, assuming for the moment that you have a field named “school” in the form, but it’s not a field in the model, your if form.is_valid(): block needs to look something like this:

if form.is_valid():
    student = form.save()
    school = form.cleaned_data['school']
    messages.success(request, "Record updated successfully!")
    return redirect('courses', student=student.id, school=school)

This implies that your url definition for the next view would be:

path('student/<int:student_id>/<int:school_id>/', views.course_selection, name='courses')

That makes the view start to look like this:

def course_selection(request, student_id, school_id):
    student = Student.objects.get(id=student_id)
    form = SelectCourseForm(school_id)
    ...

And in your form, you’ll do something like

def __init__(self, school, *args, **kwargs):
    super().__init__(self, *args, **kwargs)
    self.fields['courses'].queryset = Courses.objects.filter(school=school)

(Again, this is a skeleton and not a complete solution, but hopefully it gives you enough information to proceed.)