Django m2m形成出现的字段

时间:2010-06-11 19:11:09

标签: django forms m2m

我有课堂申请和跟随关系。用户可以互相关注并创建教室。当用户创建教室时,他只能邀请跟随他的人。 “课堂”模型是一个m2m到用户表。

我有模特。吡啶:

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作为课堂表单,默认视图考虑到我与User表的多对多关系,在字段成员中,是我数据库中所有用户的列表。 但我只希望在该列表中与登录用户建立关系的用户 - 创建教室的用户。 我怎么能这样做?

p.s:同样,当我保存表单时,它会保存,但没有“成员”

谢谢!

1 个答案:

答案 0 :(得分: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)     

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

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