选择一个有效的选择 Django Filtered Drop Down Menu

Posted

技术标签:

【中文标题】选择一个有效的选择 Django Filtered Drop Down Menu【英文标题】:Select a valid choice Django Filtered Drop Down Menu 【发布时间】:2021-04-23 23:50:05 【问题描述】:

开发人员,

在我的项目中,我有一个表单,其中有一个选择学生姓名的字段,它是当前就读于该特定班级的学生的下拉字段。它从表 Section Enrollment 获取此信息,而不是检查 master Student 表。过滤工作正常,但是当我提交表单时,它说学生姓名不是一个有效的选择。我的猜测是因为它提交的是学生姓名而不是 ID,我不能 100% 确定。这是我的模型和视图。我不知道如何解决这个问题。感谢您的帮助。


QUERY IN QUESTION:
getstudents = SectionEnrollment.objects.filter(section_id=classid).select_related().values_list('studentpsid_id__student_name', flat = True)

MODELS:

# Creation of Clas-s-rooms and Assigned Teachers 
class SectionEnrollment(models.Model):
    sectionenrollmentpsid = models.CharField(primary_key = True,max_length = 50, default = "")
    section = models.ForeignKey(Section,on_delete = models.PROTECT, default = "" ,)
    studentpsid = models.ForeignKey(Student,on_delete = models.PROTECT, default = "" ,)
    entry_date = models.DateField(blank=True)
    exit_date = models.DateField(blank=True)
    dropped = models.BooleanField(default = False, blank = True)
    

    class Meta:
       verbose_name = "Student Section Enrollment"
    def __str__(self):
        return self.sectionenrollmentpsid     

# Where Basic Student Data Is Stored 
class Student(models.Model):
    studentpsid= models.CharField(primary_key = True , default = "", max_length = 50, unique = True)
    student_name = models.CharField(max_length = 50)
    first_name = models.CharField(max_length = 50, default = "")
    last_name = models.CharField(max_length = 50,default = "")
    gender = models.CharField(max_length = 1,default = "")
    student_grade = models.CharField(max_length = 2, default = "")
    home_room = models.CharField(max_length = 5, default = "")
    student_enrollment = models.CharField(max_length = 2, default = "")
    school_number = models.CharField(max_length = 15, default = "") 
    email = models.EmailField(default = "")
    projected_graduation_year = models.CharField(max_length = 4, default = "")
    counseling_goal = models.TextField(max_length = 255)
    win_username = models.CharField(max_length = 50)
    win_password = models.CharField(max_length = 50)
    offsite_laptop = models.BooleanField(default = False, blank = True)
    image = models.ImageField(default ="default.png", upload_to ='student_pics')

VIEW:

@login_required
def Rapid_Fire(request, classid):

 if request.method == "GET":
     date = datetime.date.today()
     class_name = Section.objects.filter(sectionpsid=classid)
     getstudents = SectionEnrollment.objects.filter(section_id=classid).select_related().values_list('studentpsid_id__student_name', flat = True)
     student_selection = getstudents.all().order_by('studentpsid__student_name')
     my_class_id = request.session['my_class_id']
     sectionpsid = Section.objects.get(sectionpsid = my_class_id)
     form = Rapid_Fire_Form()
     form.fields["student_name"].queryset = getstudents
     form.fields["sectionpsid"].queryset = class_name
     context = ('form': form, 'my_class_id': my_class_id, 'sectionpsid':sectionpsid,)
     return render(request, 'points/rapid_fire.html', context )

 elif request.method == "POST":
     date = datetime.date.today()
     class_name = Section.objects.filter(sectionpsid=classid)
     getstudents = SectionEnrollment.objects.filter(section_id=classid).select_related().values_list('studentpsid_id__student_name', flat = True)
     student_selection = getstudents.all().order_by('studentpsid__student_name')
     my_class_id = request.session['my_class_id']
     sectionpsid = Section.objects.get(sectionpsid = my_class_id)
     form = Rapid_Fire_Form(request.POST)
     form.fields["student_name"].queryset = getstudents
     form.fields["sectionpsid"].queryset = class_name
     if form.is_valid():
      # Records logged in user to table  
      obj = form.save(commit= False)
      userid = request.user
      obj.created_by = userid
      obj.save() 


【问题讨论】:

确认您使用的是 django 表单,例如 forms.ModelForm 或 HTML 表单? Django.ModelForm 。如果我取消查询的 student_name 部分,而只在列表中包含学生 ID 列表,它会告诉我,当我点击提交时,以下部分必须是 Student 表的实例。 好的,如果它是一个模型表单,那么你试图给它的字段一些价值吗?它会具有默认所需的值吗?它是由 Django 完成的 我正在查询特定班级的所有学生姓名。如果我不过滤它,那么所有学生的名字都会出现在整个系统中。我不想那样。 是的,我明白了。但是模板呢?你在迭代这些领域吗?特别是下拉菜单?要不然是啥?可以添加模板吗? 【参考方案1】:

看来问题出在这里:

 getstudents = SectionEnrollment.objects.filter(section_id=classid).select_related().values_list('studentpsid_id__student_name', flat = True)
 student_selection = getstudents.all().order_by('studentpsid__student_name')

values_list('studentpsid_id__student_name', flat = True) 正在收集学生 name 而不是他们的 id。所以我认为表单字段将是错误数据的字段。 如果我是对的,解决方案可能是:

students_id = SectionEnrollment.objects.filter(section_id=classid).select_related().values_list('studentpsid__id', flat = True)
student_selection = Student.objects.filter(id__in=students_id).order_by('student_name')

或:

student_selection = Student.objects.filter(sectionenrollment_set__section_id=classid).order_by('student_name')

【讨论】:

它想要学生表字段,它的一个实例。我刚刚做了一个测试并将查询编写为 getstudentsall = Students.objects.all() 工作正常。然而,这并不限制学生上课。我必须重写我的原始查询,但我必须从学生表开始。

以上是关于选择一个有效的选择 Django Filtered Drop Down Menu的主要内容,如果未能解决你的问题,请参考以下文章

Django表示错误:选择一个有效的选择。这种选择不是可用的选择之一

zepto源码--filtered, contains,funcArg,setAttribute,className,deserializeVale--学习笔记

将 ajax 与 django 表单一起使用时,出现错误“选择一个有效的选择。这不是可用的选择之一。”

text select2 django选择有效的选项选项错误

表单 ModelChoiceField 查询集 + 额外选择字段 django 表单

检查特定实例是不是存在的更好选择 django