Home > Blockchain >  How to get id from created object in Django
How to get id from created object in Django

Time:12-17

I have models: Group and Members. Groups have many members, but when a Group is created, currentUser automatically becomes a Member. I'm doing everything in single request and I have problem with getting id createdGroup.

My models:

class Group(models.Model):
    groupName = models.CharField(max_length=100)
    description = models.CharField(max_length=255)
    inviteKey = models.UUIDField(default=uuid.uuid4,
                                 unique=True,
                                 editable=False)

class Members(models.Model):
    userId = models.ForeignKey(User, on_delete=models.CASCADE)
    groupId = models.ForeignKey(Group, on_delete=models.CASCADE)

Form:

class GroupForm(forms.ModelForm):
    groupName = forms.CharField(label='Name', max_length=100)
    description = forms.CharField(label='Description', max_length=255)
    inviteKey: forms.CharField(label='Invite Key')

    class Meta:
        model = Group
        fields = ['groupName', 'description']

View:

def createGroup(request):
    if request.method == "POST":
        form = GroupForm(request.POST)
        if form.is_valid():
            form.save()
            currentUser = request.user
            print('group id', request.POST.get('id', ''))
            #after group creation i would add current member
            addMember(currentUser, True, True) # should be currentUser, createdGroup, True
            messages.success(request, f'Group created')
            return redirect('/')
    else:
        form = GroupForm()
        
    return render(request, 'group/createGroup.html',{'form': form})

How can I get the newly created Group's id? I've tried something like this:

group = request.POST.get('id', '')

When I console.log(request.POST) I'm getting only (name, description)

CodePudding user response:

try this:

new_group = form.save()
id = new_group.id

the id is created when you save the form triggert by the request... so it can't be in the request!

  • Related