我有一个医生数据库,我想改变他们的网址结构:
当前网址为:localhost:8000/docprofile/32/
def showDocProfile(request, id):
doctor = get_object_or_404(Doctor, id=id)
d = getVariables(request,dictionary={'page_name': "Dr." + doctor.name+"" })
d.update({'doctor': doctor, 'doctors': Doctor.objects.all()})
return render(request, 'm1/docprofile.html', d)
url(r'^docprofile/(?P<id>\d+)/$', views.showDocProfile, name='showDocProfile'),
新网址为localhost:8000/doctor/john-doe/
def showDocProfile(request, slug):
doctor = get_object_or_404(Doctor, slug=slug)
d = getVariables(request,dictionary={'page_name': "Dr." + doctor.name+"" })
d.update({'doctor': doctor, 'doctors': Doctor.objects.all()})
return render(request, 'm1/docprofile.html', d)
url(r'^doctor/(?P<slug>[\w-]+)/$', views.showDocProfile, name='showDocProfile'),
我成功更改了网址。
我的问题是如何进行永久性301网址重定向,以便有人访问localhost:8000/docprofile/32/
时重定向到localhost:8000/doctor/john-doe/
?
答案 0 :(得分:2)
将这些添加到您的文件中。
<强> Views.py 强>
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
def showDocProfileOld(request, id):
doctor = get_object_or_404(Doctor, id=id)
return HttpResponseRedirect(reverse('showDocProfile', args=[doctor.slug]))
def showDocProfile(request, slug):
doctor = get_object_or_404(Doctor, slug=slug)
d = getVariables(request,dictionary={'page_name': "Dr." + doctor.name+"" })
d.update({'doctor': doctor, 'doctors': Doctor.objects.all()})
return render(request, 'm1/docprofile.html', d)
<强> urls.py 强>
url(r'^doctor/(?P<slug>[\w-]+)/$', views.showDocProfile, name='showDocProfile'),
url(r'^docprofile/(?P<id>\d+)/$', views.showDocProfileOld, name='showDocProfileOld'),