Debujang Debujang - 1 year ago 263
Python Question

How to use redirect with parameter in Django?

I have this function in

def detel_kar(request, id):
detel = {}
detel['detels'] = DipPegawai.objects.filter(PegID=id)
return render(request, 'karyawan/detel_kar.html', detel)

I then have a function to insert data with parameter id by getting a primary key from elsewhere.

def tambah_kel(request, id):
kar = DipPegawai.objects.get(PegID=id)
if request.method == "POST":
form = datakeluarga(request.POST,instance=kel)
if form.is_valid():
return redirect('detel_kar')
form = datakeluarga()
return render(request, 'karyawan/tambah_kel.html', {'form': form, 'kars': kar})

How to redirect to
view? if i use this code in

return redirect('detel_kar')

it will return anerror

Reverse for 'detel_kar' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

from django.conf.urls import url
from . import views
url(r'^$', views.index, name='index'),
url(r'^tambah/$', views.tambah, name='tambah_kar'),
url(r'^karyawan/detel_kar/(?P<id>\d+)/$',views.detel_kar, name='detel_karyawan'),
url(r'^karyawan/edit_kar/(?P<id>\d+)/$',views.edit_kar, name='edit_karyawan'),
url(r'^karyawan/del_kar/(?P<id>\d+)/$',views.del_kar, name='del_karyawan'),
url(r'^karyawan/tambah_kel/(?P<id>\d+)/$',views.tambah_kel, name='tambah_keluarga'),

Answer Source

In your, you have defined:

url(r'^karyawan/detel_kar/(?P<id>\d+)/$',views.detel_kar, name='detel_karyawan'),

i.e., the view that calls the function detel_kar() is named 'detel_karyawan'. This is the name you need to use in your redirect:

return redirect('detel_karyawan')

However the view expects an ID, so you must supply an ID when calling it:

return redirect('detel_karyawan', id=id)

(Where id is determined based on the logic in your view).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download