Gusan
Gusan

Reputation: 431

How to use redirect with parameter in Django?

I have this function in views.py:

def detel_kar(request, id):
   detel = {}
   detel['detels'] = DipPegawai.objects.filter(PegID=id)
   detel['kels']=DipKeluargaPeg.objects.filter(PegID_id=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":
       kel=DipKeluargaPeg(PegID=kar)
       form = datakeluarga(request.POST,instance=kel)
       if form.is_valid():
           form.save(commit=True)
           return redirect('detel_kar')
   else:
       form = datakeluarga()
   return render(request, 'karyawan/tambah_kel.html', {'form': form, 'kars': kar})

How to redirect to detel_kar view? if i use this code in tambah_kel function

return redirect('detel_kar')

it will return anerror

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

urls.py

from django.conf.urls import url
from . import views
urlpatterns=[
    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'),
]

Upvotes: 1

Views: 90

Answers (1)

solarissmoke
solarissmoke

Reputation: 31504

In your urls.py, 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).

Upvotes: 1

Related Questions