Daniel Czerepak
Daniel Czerepak

Reputation: 73

Django redirect to created post after form

I want to redirect to the post i actually created. So i have form, that added a post to the website, and after submit form i would like to redirect to this post. This is my urls

urlpatterns = [
    path('', views.home, name='home'),
    path('detail/<int:pk>/', views.detail, name='detail'),
    path('form/', views.formularz, name='formularz'),]

and my views :

def formularz(request):
    form = NewJobForm(request.POST)  
    if form.is_valid():
        firma = form.save(commit=False)
        firma.save() 
        return redirect('search:home')
    else:
        firma = NewJobForm() 
    context = {
            'form': form,

    }

    return render(request, 'search/home-form.html', context)

I understand how redirect is working, but have no idea how to redirect to the int:pk page

Upvotes: 2

Views: 1425

Answers (2)

Arjun Shahi
Arjun Shahi

Reputation: 7330

You can do it like this.

 if form.is_valid():
      firma = form.save()
      return redirect('detail', firma.pk)

Upvotes: 2

Alex
Alex

Reputation: 161

return redirect('/formatted/url')

will redirect you to the url you specify. I am not totally sure which URL you want to redirect to but adding that code will redirect your user to that specific URL. You can also pass in whatever variable you wanted to as you format your URL string.

Upvotes: 0

Related Questions