Django redirect to created post after form

心已入冬 提交于 2021-01-29 05:18:18

问题


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


回答1:


You can do it like this.

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



回答2:


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.



来源:https://stackoverflow.com/questions/63057718/django-redirect-to-created-post-after-form

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!