我有一个课堂应用程序和一个关注关系。用户可以互相关注,也可以创建教室。用户创建教室时,只能邀请关注他的人。Classroom 模型是一个 m2m 到 User 表。
我有模型。py:
class Classroom(models.Model):
creator = models.ForeignKey(User)
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")
并在以下应用程序的 models.py 中:
class Relations(models.Model):
initiated_by = models.ForeignKey(User, editable=False)
date_initiated = models.DateTimeField(auto_now=True, editable = False)
follow = models.ForeignKey(User, editable = False, related_name = "follow")
date_follow = models.DateTimeField(auto_now=True, editable = False)
在课堂应用程序的 views.py 中:
def save_classroom(request, username):
if request.method == 'POST':
u = User.objects.get(username=username)
form = ClassroomForm(request.POST, request.FILES)
if form.is_valid():
new_obj = form.save(commit=False)
new_obj.creator = request.user
r = Relations.objects.filter(initiated_by = request.user)
# new_obj.members =
new_obj.save()
return HttpResponseRedirect('.')
else:
form = ClassroomForm()
return render_to_response('classroom/classroom_form.html', {
'form': form,
},
context_instance=RequestContext(request))
我使用 ModelForm 作为课堂表单,考虑到我与用户表的多对多关系,在字段成员中,默认视图是我的数据库中所有用户的列表。但我只希望在该列表中与登录用户有关注关系的用户 - 创建教室的用户。我怎样才能做到这一点?
ps:另外,当我保存表单时,它会保存,但没有“成员”
谢谢!