I am trying to save the choices(COURSES_CHOICES) selected by the department in the database and populate(check/select) the same using the data saved in the database.
model.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
I use a ModelMultiChoiceField in order for the department to enroll the courses at once into the ManyToManyField bt i keep on getting this error "Select a valid choice. <QuerySet [<Choices: analysis>, <Choices: numerical>, <Choices: networking>, <Choices: philosophy>]> is not one of the available choices."
forms.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']
view.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})
Please I don't know where am getting it wrong. Thanks in Advance. Pls don't mind my indentation here
更改return str(self.courses)
以return self.courses
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.