Redirect after Form

27 views
Skip to first unread message

Stanislav Vasko

unread,
Oct 30, 2016, 8:59:34 AM10/30/16
to Django users
Greetings,

trying to create new app with simple Form to create and update Company info. My view looks like:

def company_new(request):
if request.method == "POST":
form = CompanyForm(request.POST)
if form.is_valid():
company = form.save(commit=False)
company.save()
return redirect('views.company_detail', pk=company.pk)
else:
form = CompanyForm()
return render(request, 'crm/company_edit.html', {'form': form})

with urls.py:


app_name = 'crm'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^index_previous', views.index_previous, name='index_previous'),
url(r'^report_money', views.report_money, name='report_money'),
url(r'^report_works', views.report_works, name='report_works'),
url(r'^company/(?P<pk>[0-9]+)/$', views.company_detail, name='company_detail'),
url(r'^work/(?P<pk>[0-9]+)/$', views.work_detail, name='work_detail'),
url(r'^company/new/$', views.company_new, name='company_new'),
url(r'^company/edit/(?P<pk>[0-9]+)/$', views.company_edit, name='company_edit'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


But when i save my new company, i get info: 

Page not found (404)

Request Method:GET
Request URL:http://localhost:8000/company/new/views.company_detail


So Django takes whole URL + my redirect. Is it possible to force to use my urls.py? I found something like "return HttpResponseRedirect('/')", but it's strange solution. Another way is to point to exact path, but i don't like too, i'd like to use urls.py to redirect.

Thanks for tips, i hope it's some simple trick or import i'm missing.

Moreplavec

unread,
Oct 30, 2016, 9:39:19 AM10/30/16
to Django users
I found in Django Tutorial solution: https://docs.djangoproject.com/en/1.10/intro/tutorial04/ :

Now i have: 

return HttpResponseRedirect(reverse('crm:company_detail', args=(company.pk,)))
#return redirect('views.company_detail', pk=company.pk)

And it works fine!

Michal Petrucha

unread,
Oct 31, 2016, 5:21:37 AM10/31/16
to django...@googlegroups.com
Just for the record, you should also be able to use this::

return redirect('crm:company_detail', company.pk)

(That should be equivalent to the explicit HttpResponseRedirect with
reverse().)

Cheers,

Michal
signature.asc

Moreplavec

unread,
Oct 31, 2016, 10:30:20 AM10/31/16
to Django users
Many thanks, works fine and looks much better to me.

Dne pondělí 31. října 2016 10:21:37 UTC+1 Michal Petrucha napsal(a):
Reply all
Reply to author
Forward
0 new messages