我尝试保存来自multiplechoiceField的数据,但是只保存了一项。当只有一个项目没有问题时,当有多个项目时,只有最后一个项目被保存
models.py
class Reservation( models.Model):
date_de_reservation = models.DateTimeField('Date de reservation', auto_now = True)
type_enseignement = models.CharField('Type enseignement', max_length = 10, choices = (("cm", "CM"), ("td", "TD"), ("tp", "TP"), ("tc","TC")), )
date_du_jour_reserve = models.DateField("Date du jour reservé")
plage_horaire = models.ForeignKey("Plage_Horaire", on_delete = models.CASCADE )
cours = models.ForeignKey(Cours, on_delete = models.CASCADE)
enseignant = models.ForeignKey(Enseignant, on_delete = models.CASCADE)
sallecours = models.ForeignKey(SalleCours, on_delete = models.CASCADE, blank = True, null = True)
option = models.ForeignKey(Option,on_delete = models.CASCADE )
valide = models.BooleanField(blank = True, default = False)
analyse = models.BooleanField(blank = True , default =False )
forms.py
class Reservation_Form(forms.ModelForm):
faculte=forms.ModelChoiceField(label="Faculte", queryset=Faculte.objects.all())
departement=forms.ModelChoiceField(label="Département", queryset=Departement.objects.all())
filiere=forms.ModelChoiceField(label="Filière", queryset=Filiere.objects.all())
niveau = forms.ModelChoiceField(label = 'Niveau', queryset = Niveau.objects.all() )
option=forms.ModelChoiceField(label="Option", queryset=Option.objects.all())
semestre=forms.ModelChoiceField(label='Semestre', queryset=Semestre.objects.all())
plage_horaire = forms.ModelMultipleChoiceField(label="", queryset = Plage_Horaire.objects.all())
class Meta:
model=Reservation
exclude=('date_de_reservation', 'sallecours', 'valide', 'enseignant','plage_horaire' )
widgets={
'date_du_jour_reserve': DateInput(),
}
views.py
def reservation(request):
f=Reservation_Form()
if request.method=='POST':
f=Reservation_Form(request.POST)
print (f.is_valid())
print(request.POST.getlist('plage_horaire') )
if f.is_valid() :
res = f.save(commit=False)
plage_horaire = f.cleaned_data['plage_horaire']
for i in plage_horaire:
res.plage_horaire=i
res.save()
return redirect('configuration:ma_reservation')
答案 0 :(得分:1)
您不能保存多个值,因为您只有一个字段可以输入此值。
当您这样做:
for i in plage_horaire:
res.plage_horaire=i
每一个小故事都会覆盖您的价值。
为此,您需要在ManyToManyField
中输入plage_horaire
。
更多信息,Django Docs