2017-06-26 50 views
1

我的Django應用程序中的CreateView有問題,我想創建一個Sesion,但會話只能由該組的GroupMember領導者創建。Django:無法在指定中介模型的ManyToManyField上設置值

這裏是我的模型:

class Group(models.Model): 
    # The code 

class GroupMember(models.Model): 
    member = models.ForeignKey(Volunteer) 
    group = models.ForeignKey(Group) 
    leader = models.BooleanField(default=False) 

class Session(models.Model): 
    name = models.CharField(max_length=250) 
    group = models.ForeignKey(Group) 
    assistants = models.ManyToManyField(GroupMember, through='SessionAssistant') 
    hours = models.FloatField(default=1) 
    day = models.DateTimeField(default=datetime.now) 

class SessionAssistant(models.Model): 
    assistant = models.ForeignKey(GroupMember) 
    session = models.ForeignKey(Session) 
    rol = models.CharField(max_length=250) 
    assist = models.BooleanField(default=True) 

此外,我想,當我創建一個Sesision我可以將我的助手德ROLS,這裏是我的觀點:

class CreateSession(CreateView): 
model = Session 
template_name = "session_form.html" 
fields = ['name', 
      'hours', 
      'day', 
      'assistants', ] 

success_url = '/' 

def form_valid(self, form): 
    group = Group.objects.get(id=self.kwargs['pk']) 
    form.instance.group = group 
    return super(CreateSession, self).form_valid(form) 

回答

0

Django不保存自定義ManyToMany關係。看看official documentation

可以使用

form.save() 

保存表單,然後從SessionAssistant

for assistant in form.cleaned_data['assistants']: 
    SessionAssistant.objects.create(assistant=assistant, session=form.instance) 
創建新對象
相關問題