我有这样的模型:
class GuestStatus(models.Model):
guest_status = models.CharField(max_length=200)
arrangement = models.IntegerField(unique=True, help_text="Start from 1. Guest status will be arranged alphabetically.")
class Guest(models.Model):
user = models.ForeignKey(User)
full_name = models.CharField(max_length=250)
status = models.ManyToManyField(GuestStatus, blank=True, null=True)
invitation_date = models.DateTimeField(blank=True, null=True)
我想ManyToManyField
显示为复选框。这就是为什么我这样做:
class GuestForm(ModelForm):
status = forms.ModelMultipleChoiceField(queryset=GuestStatus.objects.all().order_by('arrangement'), widget=forms.CheckboxSelectMultiple, required=False)
class Meta:
model = Guest
exclude = ['user', 'invitation_date']
我正在尝试保存这样的表格:
form = GuestForm(request.POST)
if form.is_valid():
status = form.cleaned_data['status']
guest.status = status
if status:
invitation_date = datetime.now()
else:
invitation_date = None
new_guest = form.save(commit=False)
new_guest.user = request.user
new_guest.save()
new_guest.status = status
form.save_m2m()
return HttpResponseRedirect('/list_guests/')
该表单正在保存所有数据,但不保存status
值。怎么了?另外,成功保存后如何访问模板中的状态值?谢谢