我在Django应用程序中遇到CreateView问题,我想创建一个Sesion,但会话只能由该组的GroupMember领导创建。
以下是我的模特:
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时可以分配我的助手,这是我的观点:
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 :(得分:2)
Django不保存自定义ManyToMany
关系。看看official documentation。
您可以使用
保存表单form.save()
然后从SessionAssistant
for assistant in form.cleaned_data['assistants']:
SessionAssistant.objects.create(assistant=assistant, session=form.instance)