我创建了一个模板,该模板呈现了学生的下拉列表。
我想过滤另一个视图上的查询集,以仅显示所选学生的日程表信息。
student_list中的perm_id是主键,而StudentSchedule中的perm是外键。
以下是我的models.py,forms.py和views.py的片段
models.py
class StudentList(models.Model):
student_name = models.CharField(max_length=45, blank=True, null=True)
perm_id = models.IntegerField(primary_key=True)
class StudentSchedule(models.Model):
perm = models.ForeignKey(StudentList, on_delete=models.CASCADE)
begin_period = models.CharField(max_length=45, blank=True, null=True)
section_id = models.CharField(max_length=45, blank=True, null=True)
course_title = models.CharField(max_length=45, blank=True, null=True)
last_name1 = models.CharField(max_length=45, blank=True, null=True)
forms.py
class StudentForm(forms.Form):
Student = forms.ModelChoiceField(queryset=StudentList.objects.all()
.order_by('student_name'))
views.py
class ScheduleView(View):
form_class = ScheduleForm
template_name = 'learning_logs/student_schedule.html'
def get(self, request):
form = self.form_class(initial={})
data = StudentSchedule.objects.filter()
return render(request, self.template_name, {'form': form, 'data':
data})
我可以执行以下操作,让ID为123456的学生
data = StudentSchedule.objects.filter(perm=123456)
但是,我希望Django使用从StudentList中选择的学生的perm_id
我的网址如下:
# Page for selecting a student from drop down list
path('select_student/', views.StudentView.as_view(), name='select_student'),
# Page for displaying student schedule
path('student_schedule/<int:pk>/$', views.ScheduleView.as_view(),
name='student_schedule'),
答案 0 :(得分:0)
说您的路径就像
urlpatterns = [
path('students/<int:pk>/$', views.ScheduleView.as_view(), name='student-detail'),
...
]
然后您将在get方法中获得一个附加参数,您可以通过以下方式访问该参数
class ScheduleView(View):
form_class = ScheduleForm
template_name = 'learning_logs/student_schedule.html'
def get(self, request, pk):
form = self.form_class(initial={})
data = StudentSchedule.objects.filter(perm=pk)
return render(request, self.template_name, {'form': form, 'data':
data})
而且在您的student_schedule.html
中,您还需要perm.id才能以
{% url ... perm.id%}