1

我有这样的模型:

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值。怎么了?另外,成功保存后如何访问模板中的状态值?谢谢

4

1 回答 1

0

我会这样做:

form = GuestForm(request.POST)
if form.is_valid():
    if status:
        invitation_date = datetime.now() 
    else:
        invitation_date = None

    new_guest = form.save(commit=False)
    new_guest.user = request.user
    new_guest.save()

    status = form.cleaned_data['status']
    for stat in status:
        new_guest.status_set.create(guest_status = stat['guest_status'], arrangement = stat['arrangement'])

    return HttpResponseRedirect('/list_guests/')

获得new_guest实例后,您创建GuestStatus实例并将它们绑定到new_guest.

或者,如果GuestStatus是您的字典,您可以:

    for stat in status:
        gs = GuestStatus.objects.get(pk = stat['guest_status'])
        new_guest.status_set.add(gs)

希望你理解我和我的英语:)

于 2013-10-28T09:13:27.513 回答