Django m2m 表单显示字段

发布于 2024-09-04 22:43:48 字数 1726 浏览 2 评论 0原文

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

我有模型。 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 作为课堂表单和默认视图,考虑到我与 User 表的多对多关系,在“成员”字段中,是我的数据库中所有用户的列表。 但我只想在该列表中与登录用户(创建教室的用户)具有关注关系的用户。 我怎样才能做到这一点?

ps:另外,当我保存表单时,它会保存,但没有“成员”,

谢谢!

I have a classroom application,and a follow relation. Users can follow each other and can create classrooms.When a user creates a classroom, he can invite only the people that are following him.
The Classroom model is a m2m to User table.

i have in models. 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")

and in models.py of the follow application:

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)

and in views.py of the classroom app:

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))  

i'm using a ModelForm for the classroom form, and the default view, taking in consideration my many to many relation with User table, in the field Members, is a list of all Users in my database.
But i only want in that list the users that are in a follow relationship with the logged in user - the one who creates the classroom.
How can i do that?

p.s: also, when i'm saving the form, it saves, but without "members"

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

等风也等你 2024-09-11 22:43:48

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

    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)     

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

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

You have to change the queryset that is used to populate the formfield... Put the following in your form class:

    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])

To get the current user into the form's __init__ method, change its initsialisation in your save_classrom view:

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

I'm not quite sure about the query to get the users for your field, but i think it should be checked that initiated_by is the logged in user?

To save the m2m relations you also have to call form.save_m2m()!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文