1

我有一个课堂应用程序和一个关注关系。用户可以互相关注,也可以创建教室。用户创建教室时,只能邀请关注他的人。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:另外,当我保存表单时,它会保存,但没有“成员”

谢谢!

4

1 回答 1

1

您必须更改用于填充表单域的查询集...将以下内容放入表单类中:

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(ClassroomForm, self).__init__(*args, **kwargs)
        relations = Relations.objects.filter(initiated_by=user)
        self.fields["members"].queryset = \
            User.objects.filter(pk__in=[r.follow.pk for r in relations])

要让当前用户进入表单的方法,请在您的视图__init__中更改其初始化:save_classrom

        form = ClassroomForm(request.POST, request.FILES, user=request.user) 
        # and after the else:
        form = ClassroomForm(user=request.user)     

我不太确定为您的字段获取用户的查询,但我认为应该检查 Initial_by 是登录用户吗?

要保存 m2m 关系,您还必须致电form.save_m2m()

于 2010-06-12T12:11:06.597 回答