# Using a Select filter to narrow choices for a form.

**URL:** <https://forum.djangoproject.com/t/using-a-select-filter-to-narrow-choices-for-a-form/33530>\
**Category:** Forms & APIs\
**Created:** [August 3, 2024, 4:34pm UTC](https://forum.djangoproject.com/t/using-a-select-filter-to-narrow-choices-for-a-form/33530 "2024-08-03T16:34:01Z")\
**Posts on this page:** 11\
**Page:** 2

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [August 15, 2024, 12:57am UTC](https://forum.djangoproject.com/t/using-a-select-filter-to-narrow-choices-for-a-form/33530/21 "2024-08-15T00:57:06Z")

</div>

> [@Coolmike890](#):
>
> I did this and got: " NameError at /student/UoW
> 
> name ‘SelectCourseForm’ is not defined"

Please post the actual code you are trying here.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [August 15, 2024, 12:58am UTC](https://forum.djangoproject.com/t/using-a-select-filter-to-narrow-choices-for-a-form/33530/22 "2024-08-15T00:58:25Z")

</div>

> [@anefta](#):
>
> ```auto
> urlpatterns = [
> path('student/int:school_id', views.course_selection, name='courses'), # Use int instead of str
> ]
> 
> ```

Side note: That path should be `'student/<str:school_id>/'`, because the primary key of the `School` model is a string.

---

<div class="post-metadata">

**Author:** ![Coolmike890](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/coolmike890/32/19565_2.png) [@Coolmike890](https://forum.djangoproject.com/u/Coolmike890)\
**Post date:** [August 15, 2024, 1:14am UTC](https://forum.djangoproject.com/t/using-a-select-filter-to-narrow-choices-for-a-form/33530/23 "2024-08-15T01:14:10Z")

</div>

Sure thing.

The url:

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

The views:

```auto
def choose_school7(request):
	
	
		aschool = Courses.objects.all()
		form=SelectSchoolForm(request.POST)
		if request.method == "POST":
			if form.is_valid():
				school = form.cleaned_data['school']
				messages.success(request, "School chosen successfully!")

				return redirect('courses', school_id=school.id)
		context = {'form': form, 'aschool':aschool}  
		return render(request, 'choose_school7.html', context)	

def course_selection(request, school_id):

		form = SelectCourseForm(school_id, request.POST or None)
		if form.is_valid():
			form.save()
			messages.success(request, "Record added successfully!")
			return redirect('school')
		context = {'form':form}
		return render(request, 'course_selection.html', context)

```

and the forms:

```auto
class SelectSchoolForm(forms.ModelForm):

        class Meta:
                model = Courses
                fields = ('school', )
                labels = {'school':'School', }
                widgets = {'school': forms.Select(attrs={"placeholder":"School", "class":"form-select"}),

                 }

class SelectCourseForm(forms.ModelForm):

			def __init__ (self, school, *args, **kwargs):
				super(). __init__ (self, *args, **kwargs)
				self.fields['course'].queryset = Courses.objects.filter(school_id=school)
                            
			class Meta:
				model = Student
				fields = ( 'student_id', 'course')
				labels = {'student_id':'', 'course':''}
				widgets = {'student_id':forms.widgets.TextInput(attrs={"placeholder":"Student ID", "class":"form-control"}),
               			'course':forms.widgets.Select(attrs={"placeholder":"Course", "class":"form-select"}),
              
               
                }

```

If there’s anything else you need, I’ll be happy to include it. Thanks.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [August 15, 2024, 1:16am UTC](https://forum.djangoproject.com/t/using-a-select-filter-to-narrow-choices-for-a-form/33530/24 "2024-08-15T01:16:53Z")

</div>

> [@Coolmike890](#):
>
> name ‘SelectCourseForm’ is not defined"

Are you importing that form in your views.py file?

---

<div class="post-metadata">

**Author:** ![Coolmike890](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/coolmike890/32/19565_2.png) [@Coolmike890](https://forum.djangoproject.com/u/Coolmike890)\
**Post date:** [August 15, 2024, 1:29am UTC](https://forum.djangoproject.com/t/using-a-select-filter-to-narrow-choices-for-a-form/33530/25 "2024-08-15T01:29:56Z")

</div>

Oh. No. Sorry. I fixed that. Now I get:

"AttributeError at /student/UoW

‘SelectCourseForm’ object has no attribute ‘get’"

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [August 15, 2024, 1:38am UTC](https://forum.djangoproject.com/t/using-a-select-filter-to-narrow-choices-for-a-form/33530/27 "2024-08-15T01:38:46Z")

</div>

Also, I just noticed:

> [@Coolmike890](#):
>
> ```auto
> def course_selection(request, school_id):
> 
> form = SelectCourseForm(school_id, request.POST or None)
> if form.is_valid():
> form.save()
> messages.success(request, "Record added successfully!")
> return redirect('school')
> context = {'form':form}
> return render(request, 'course_selection.html', context)
> 
> ```

You’re not checking for a `POST` vs `GET` request in this view. You’re checking form.is\_valid() in both circumstances.

You’re also not getting the `Student` instance to be edited by the form. (See the skeleton that I posted above at [Using a Select filter to narrow choices for a form. - #15 by KenWhitesell](https://forum.djangoproject.com/t/using-a-select-filter-to-narrow-choices-for-a-form/33530/15))

---

<div class="post-metadata">

**Author:** ![anefta](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/anefta/32/10649_2.png) [@anefta](https://forum.djangoproject.com/u/anefta)\
**Post date:** [August 15, 2024, 8:25am UTC](https://forum.djangoproject.com/t/using-a-select-filter-to-narrow-choices-for-a-form/33530/28 "2024-08-15T08:25:58Z")

</div>

Oops! I missed that! Thank you for pointing out @KenWhitesell

---

<div class="post-metadata">

**Author:** ![Coolmike890](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/coolmike890/32/19565_2.png) [@Coolmike890](https://forum.djangoproject.com/u/Coolmike890)\
**Post date:** [August 15, 2024, 9:12am UTC](https://forum.djangoproject.com/t/using-a-select-filter-to-narrow-choices-for-a-form/33530/29 "2024-08-15T09:12:22Z")

</div>

So I’ve added in the if request.method == “POST”: but I still have the error: "AttributeError at /student/UoW

‘SelectCourseForm’ object has no attribute ‘get’"

For completeness, that view is now:

```auto
def course_selection(request, school_id):

		form = SelectCourseForm(school_id, request.POST or None)
		if request.method == "POST":
			if form.is_valid():
				form.save()
				messages.success(request, "Record added successfully!")
				return redirect('school')
		context = {'form':form}
		return render(request, 'course_selection.html', context)

```

Ken: I’m not sure what you mean by “You’re also not getting the `Student` instance to be edited by the form. (See the skeleton that I posted above”. I don’t understand why I need the student id to be passed at all, we’re creating a new instance of student, not updating a student.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [August 15, 2024, 3:09pm UTC](https://forum.djangoproject.com/t/using-a-select-filter-to-narrow-choices-for-a-form/33530/30 "2024-08-15T15:09:15Z")

</div>

Your view needs _both_ the student being edited _and_ the school selected.

> [@KenWhitesell](#):
>
> ```auto
> def course_selection(request, student_id, school_id):
> student = Student.objects.get(id=student_id)
> form = SelectCourseForm(school_id)
> ...
> 
> ```

> [@Coolmike890](#):
>
> I don’t understand why I need the student id to be passed at all, we’re creating a new instance of student, not updating a student.

Didn’t you create the student in the previous view? By the time you get to _this_ view, it’s no longer a “new” student, it’s an “existing” student.

---

<div class="post-metadata">

**Author:** ![Coolmike890](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/coolmike890/32/19565_2.png) [@Coolmike890](https://forum.djangoproject.com/u/Coolmike890)\
**Post date:** [August 20, 2024, 3:23am UTC](https://forum.djangoproject.com/t/using-a-select-filter-to-narrow-choices-for-a-form/33530/31 "2024-08-20T03:23:12Z")

</div>

Sorry - I missed your reply. You’re right. We shouldn’t be saving the form above. Just selecting the school. In any case, I do not see where the student is being created. The form only has the school selection in it.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [August 20, 2024, 3:39am UTC](https://forum.djangoproject.com/t/using-a-select-filter-to-narrow-choices-for-a-form/33530/32 "2024-08-20T03:39:13Z")

</div>

I’m sorry, I guess I’ve gotten lost among all the different views. If you’re entering the student id on this same form as the filtered course, then you wouldn’t need to query for t.

[Previous page](https://forum.djangoproject.com/t/using-a-select-filter-to-narrow-choices-for-a-form/33530.md?page=1)
