指定中介模型的ManyToManyField上设置值

指定中介模型的ManyToManyField上设置值

我正在以相同的形式保存两个表-具有m2m关系。
我没有成功,但错误仍然存​​在,例如:无法在指定中介模型的ManyToManyField上设置值。改用成员(member)管理器
成员资格是我的“通过表”。

我的代码:

def save_classroom(request):
   classroom_instance = Classroom()
   if request.method == 'POST':
        form = ClassroomForm(request.POST, request.FILES, user = request.user)
        if form.is_valid():
           new_obj = form.save(commit=False)
           new_obj.user = request.user
           new_obj.save()
           membership = Membership(member = request.user,classroom=new_obj)
           membership.save()
           form.save_m2m()
           return HttpResponseRedirect('.')
   else:
           form = ClassroomForm(user = request.user)
   return render_to_response('classroom/classroom_form.html', {
           'form': form,

           },
          context_instance=RequestContext(request))

我的模特:
class Classroom(models.Model):
     user = models.ForeignKey(User, related_name = 'classroom_creator')
     classname = models.CharField(max_length=140, unique = True)
     date = models.DateTimeField(auto_now=True)
     open_class = models.BooleanField(default=True)
     members = models.ManyToManyField(User,related_name="list of invited members", through = 'Membership')

class Membership(models.Model):
      accept = models.BooleanField(default=False)
      date = models.DateTimeField(auto_now = True)
      classroom = models.ForeignKey(Classroom, related_name = 'classroom_membership')
      member = models.ForeignKey(User, related_name = 'user_membership')

我哪里错了?

最佳答案

如上所示:

http://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany



我猜您的代码在“form.save_m2m()”行上跳了起来,这是不必要的,因为您已经手动创建了成员资格。

关于django - django无法在用于指定中介模型的ManyToManyField上设置值。改用Manager,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3091328/

10-13 09:38