简体   繁体   中英

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

You can do it like this.

 if form.is_valid():
      firma = form.save()
      return redirect('detail', firma.pk)
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.

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