Home > Enterprise >  redirect to created object after form submission
redirect to created object after form submission

Time:10-03

Goal: To redirect to the 'build log' after the form is submitted

view:

@login_required
def buildLogCreate(request,  pk):

    post = Post.objects.get(pk=pk)
   
    if request.user.id != post.author_id:
        raise PermissionDenied()

    currentUser = request.user
    form = BuildLogForm()
    if request.method == 'POST':
        form = BuildLogForm(request.POST, request.FILES)
        if form.is_valid():
            formID = form.save(commit=False)
            formID.author = request.user
            formID.post_id = pk
            formID.save()
            return redirect('build-log-view', formID.pk)
            
    context = { 'form':form,  }

    return render(request, 'blog/buildlog_form.html', context)

The url structure setup is post->buildlog(subpost) ie: /post/118/build-log/69/

The form gets successfully submitted but I get the error NoReverseMatch at /post/118/build-log-form/ Reverse for 'build-log-view' with arguments '(69,)' What confuses me is the url is still on the post form and not build log view but the argument 69 is the correct build log id so it should be working.

url to be redirected to

path('post/<int:pk>/build-log/<int:pkz>/', views.BuildLogDisplay, name='build-log-view'),

CodePudding user response:

The URL pattern has two parameters: the primary key of the post object, and the primary key of the build log.

You can thus pass this with:

return redirect('build-log-view', pk, formID.pk)

or with named parameters:

return redirect('build-log-view', pk=pk, pkz=formID.pk)
  • Related