Django 1.6:更改URL结构

时间:2015-10-10 09:04:55

标签: python django url redirect

我有一个医生数据库,我想改变他们的网址结构:

当前网址为:localhost:8000/docprofile/32/

旧views.py

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)

old urls.py

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

新网址为localhost:8000/doctor/john-doe/

new views.py

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)

new urls.py

url(r'^doctor/(?P<slug>[\w-]+)/$', views.showDocProfile, name='showDocProfile'),

我成功更改了网址。

我的问题是如何进行永久性301网址重定向,以便有人访问localhost:8000/docprofile/32/时重定向到localhost:8000/doctor/john-doe/

1 个答案:

答案 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'),