我正在尝试将部门选择的选项(COURSES_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})
请我不知道哪里弄错了。提前致谢。请不要介意我在这里缩进