Home > Mobile >  how to link User to Model from CreateView?
how to link User to Model from CreateView?

Time:07-15

I am trying to build an application that allows user Accounts to create, join, leave, update (if they have auth) and delete Groups. The issue I'm running into is figuring out a way to link the two models so that Accounts will display the Groups they've created.

users/models.py:

class Account(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    joined_groups = models.ManyToManyField(Group, related_name='joined_group')
    created_groups = models.ManyToManyField(Group, related_name='created_group') 

group/models.py

class Group(models.Model):
   leader = models.ForeignKey(User, on_delete=models.CASCADE)
   name = models.CharField(max_length=55)
   description = models.TextField()
   joined = models.ManyToManyField(User, related_name='joined_group', blank=True)

I was able to figure out a way to have Accounts join Groups:

def join_group(request, pk):
    id_user = request.user.id
    group = Group.objects.get(id=request.POST.get('group_id'))
    account = Account.objects.get(user_id=id_user)
    if group.joined.filter(id=request.user.id).exists():
        group.joined.remove(request.user)
        account.joined_groups.remove(group)  
    else: 
        group.joined.add(request.user)
        account.joined_groups.add(group) 
    return HttpResponseRedirect(reverse('group_detail', args=[str(pk)]))

And that worked well enough. Accounts could now join Groups and display the Groups they joined. But, how do you add a Group as the Group is being created?

views.py:

class CreateGroup(CreateView):
    model = Group
    form_class = ChaburahGroup
    template_name = 'create_group.html'

How do I add a function to add Groups to an Accounts created_groups after (or as) the Group is created? Furthermore, is there a way to add the leader (creator) of the Group to the Group right after creation, so there's no need for a leader to join their own Group?

Sorry if there isn't enough code to go by, if anything else is needed, I'll add it.

CodePudding user response:

You can do anything in a form_valid method. If I understand what is needed correctly...

def form_valid( self, form):

    instance = form.save()
    instance.joined.add( self.request.user) # add the creating user to the group

    account = self.request.user.account
    account.created_groups.add( instance)

    return redirect( ... )
  • Related