3
#Models:
class GuestStatus(models.Model):
    guest_status = models.CharField(max_length=200)

    def __unicode__(self):
        return self.guest_status

    class Meta:
        verbose_name = "Guest Status"
        verbose_name_plural = "Guest Statuses"

class Guest(models.Model):
    '''
        Guest information and status
    '''
    user = models.ForeignKey(User)
    full_name = models.CharField(max_length=250)
    street_address = models.CharField(max_length=250, blank=True, null=True)
    city = models.CharField(max_length=150, blank=True, null=True)
    state = models.CharField(max_length=120, blank=True, null=True)
    zip_code = models.CharField(max_length=15, blank=True, null=True)

    guests = models.IntegerField(default=2) # No of additional guest the guest can bring.
    children = models.IntegerField(default=0, blank=True, null=True)
    email = models.EmailField(blank=True, null=True)
    phone_number = models.BigIntegerField(blank=True, null=True)
    gift_description = models.CharField(max_length=128, blank=True, null=True)

    status = models.ManyToManyField(GuestStatus, blank=True, null=True)

#Views:

def post(self, request):
        form = GuestForm(request.POST)
        if form.is_valid():

            status = form.cleaned_data['status']

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

            return HttpResponseRedirect('/list_guests/')

Djangoのドキュメントで説明されているチュートリアルに従って、DjangoにManyToManyFieldを保存しようとしています。しかし、私はこのエラーが発生しています:

Traceback:
File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  115.                         response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  25.                 return view_func(request, *args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
  86.         return handler(request, *args, **kwargs)
File "/home/sachitad/thomas/wedplan/wedplan/website/views.py" in post
  283.             new_guest.status = status
File "/usr/lib/python2.7/site-packages/django/db/models/fields/related.py" in __set__
  910.         manager = self.__get__(instance)
File "/usr/lib/python2.7/site-packages/django/db/models/fields/related.py" in __get__
  897.             through=self.field.rel.through,
File "/usr/lib/python2.7/site-packages/django/db/models/fields/related.py" in __init__
  586.                                  (instance, source_field_name))

Exception Type: ValueError at /guest/
Exception Value: "<Guest: fds>" needs to have a value for field "guest" before this many-to-many relationship can be used.

どうしたの?

4

0 に答える 0