简体   繁体   中英

Filter user in django and add to a existing group

I am new to Django and I have failing on a task now for a while. I have searched in the Django docs and here for some questions but there nothing is working for me.

Here is my view:

  def user_accept(request):
      if request.method == 'POST':
        username = AddUser.objects.filter(owner=request.user).get().user_request
        group_name = Projects.objects.filter(user=request.user).get().group_url
        group = Group.objects.get(name=group_name)
        group.user_set.add(username)
        delete_user = AddUser.objects.filter(user_request=username)
        delete_user.delete()

Here is my model:

class AddUser(models.Model):
    owner = models.ForeignKey(User)
    title = models.CharField(max_length=20, default='', blank=True)
    user_request = models.CharField(max_length=30, default='')
    answer = models.BooleanField(default=False)

AddUser model is used for users to request access to a specific project. So when a user is requesting a project, data is saved to the AddUser model. The user field is set to the "owner" of the project so I can filter every project with a proper owner.

If the owner decides to accept the request my user_accept view is executed. Here is the problem, when I try to add the username into the group, I get the following error:

 invalid literal for int() with base 10: 'myusername' 

I have tried to convert the username with int(username) and tried to get the username's user_id but nothing seems to work... I think it have something to do how I filter my objects but I don't get it.

So thanks a lot for your time, and have a happy new year!

You need the user id or the user object itself to add a user with group.user_set.add .

You can either retrieve the user object from the username, provided usernames are unique and add that:

user = User.objects.get(username=user_request)
group.user_set.add(user)

Or change your AddUser model to store the requester's id via a OneToOne field or ForeignKey instead of username.

Django default groups doesn't allow you to add username into it. You have to add User objects. Try

add_user_object = AddUser.objects.filter(owner=request.user).get()
group.user_set.add(add_user_object.owner)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM