Search code examples
pythondjangomany-to-manymanytomanyfield

Adding users to the specific group in Django


I'm trying to add some users, in my Django project, to my created before group, but I know how to add to the specific group which I know the name and it's not dynamic. I would like that when I select a specific group, already add the next user. The problem is here:

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

What should I do to replace this and indicate this group which I clicked?

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 %}

Solution

  • The main issue i see here is that you are not sending the group name m.group from your html. to do so, you must add name and value to the button element in your html (and don't forget to close the button element)

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

    Then, you can retrieve this group value in your views.py by using request.POST

    g = Group.objects.get(name=request.POST['group'])