将用户添加到Django中的特定组

时间:2016-03-12 17:49:06

标签: python django many-to-many manytomanyfield

我正在尝试将我的Django项目中的一些用户添加到我之前创建的组中,但我知道如何添加到我知道名称的特定组中,并且它不是动态的。我希望当我选择一个特定的组时,已经添加了下一个用户。问题出在这里:

g = Group.objects.get(name= 'New')

我应该怎么做才能替换它并指出我点击的这个组?

views.py:

@login_required
def choose_group(request, pk):

if request.method == "POST":

    cvs = get_object_or_404(Cv, pk=pk)

    p = Person.objects.create(name=cvs.author)
    g = Group.objects.get(name= 'New')
    m = Membership.objects.create(person=p, group=g, leader=False)


    return redirect( 'proj.views.cv_detail', pk=cvs.pk )







else:
    cv = Cv.objects.filter(author = request.user)
    cvs = get_object_or_404(Cv, pk=pk)
    mem = Membership.objects.all()

    context = {

        'mem':mem,
        'cvs':cvs,
        'cv':cv
    }

    return render(request, 'choose_group.html', context)

models.py:

class Person(models.Model):
    name = models.CharField(max_length=128)

    def __str__(self):              # __unicode__ on Python 2
        return self.name


class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

    def __str__(self):              # __unicode__ on Python 2
        return self.name


class Membership(models.Model):
    person = models.ForeignKey(Person)
    leader = models.BooleanField(default=False)
    group = models.ForeignKey(Group)

choose_groups.html:

{% block profile %}

  <div class="jumbotron">
    <h3>Choose a group to add:</h3>
  </div>          

   <ul>
    {% for m in mem %}
    <form method="POST" class="post-form" >{% csrf_token %}
      <li><button type="submit" class="li1"> <b>{{ m.group }}</b></li>

    </form>
    {% endfor %}
   </ul>


{% endblock %}

1 个答案:

答案 0 :(得分:0)

我在这里看到的主要问题是你没有从你的html发送组名m.group。 为此,您必须在html中的按钮元素中添加名称和值(并且不要忘记关闭按钮元素)

<button type="submit" class="li1" name="group" value="{{m.group}}"> <b>{{ m.group }}</b></button>

然后,您可以使用request.POST

在views.py中检索此组值
g = Group.objects.get(name=request.POST['group'])