如何使用ModelMultiChoiceField

2024-04-20 12:52:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将系所选的选项(COURSES\u choices)保存在数据库中,并使用保存在数据库中的数据填充(检查/选择)相同的选项

型号.py

class Choices(models.Model):
    COURSES_CHOICES = (
        ('analysis', 'Analysis'),
        ('numerical', 'Numerical'),
        ('networking', 'Networking'),
        ('philosophy', 'Philosophy')
    )
    courses = models.CharField(max_length=100, blank=True, choices=COURSES_CHOICES, unique=True)

    class Meta:
        verbose_name = 'choice'
        verbose_name_plural = 'choices'


    def __str__(self):
        return str(self.courses)

class Department(models.Model):
    dept_name = models.CharField(max_length=50, blank=True)

    LEVEL_CHOICES = (
        ('1', '100'),
        ('2', '200'),
        ('3', '300'),
        ('4', '400')
    )
    level = models.CharField(max_length=1, blank=True, choices=LEVEL_CHOICES, default=0)
    choices = models.ManyToManyField(Choices)

    def __str__(self):
        return self.dept_name

我使用ModelMultiChoiceField,以便部门立即将课程注册到ManyToManyField bt中。我不断遇到这个错误"Select a valid choice. <QuerySet [<Choices: analysis>, <Choices: numerical>, <Choices: networking>, <Choices: philosophy>]> is not one of the available choices."

表单.py

class CoursesListForm(forms.ModelForm):
        courses = forms.ModelMultipleChoiceField(label="Courses", queryset=Choices.objects.all(),
                                                     widget=forms.CheckboxSelectMultiple)
        def __init__(self, *args, **kwargs):
                super(CoursesListForm, self).__init__(*args, **kwargs)
                self.fields['courses'].queryset=Choices.objects.all()

        class Meta:
            model = Choices
            fields = ['courses']


class DepartmentForm(forms.ModelForm):
    class Meta:
          model = Department
          fields = ['dept_name', 'level']

视图.py

def select_course(request):
    course_list = Choices.objects.all()
    if request.method == 'POST':
        form = CoursesListForm(request.POST)
        dept = DepartmentForm(request.POST)
        if form.is_valid() and dept.is_valid():
            courses = form.save(commit=False)
            courses.save()
            dept.save()
            # messages.success('Successfully Created!')
            return redirect('course_registration')

    else:
        # messages.error('Unseccessfully created!')
        form = CoursesListForm()
        dept = DepartmentForm()
    return render(request, 'course_registration.html', {'form': form, 'dept': dept})

拜托,我不知道哪里弄错了。提前谢谢。请不要介意我在这里的压痕


Tags: nameselfformtruereturnmodelsrequestdef