Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get id from created object in Django

I have models: Group and Members.
Group have many members, but when group is creating, currentUser is automaticlly 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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 i can reach 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)

>Solution :

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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading