【问题标题】:Django 1.6: Change URL structureDjango 1.6:更改 URL 结构
【发布时间】:2016-01-08 05:24:34
【问题描述】:

我有一个医生数据库,我想更改他们的 url 结构:

当前网址为: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)

旧 urls.py

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

新的网址是localhost:8000/doctor/john-doe/

新的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)

新的 urls.py

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

我成功更改了网址。

我的问题是如何进行永久的 301 url 重定向,这样如果有人访问 localhost:8000/docprofile/32/,它就会被重定向到 localhost:8000/doctor/john-doe/

【问题讨论】:

  • 保留旧网址和旧视图,每当有请求时,请从旧视图重定向到新网址。
  • @GeoJacob 我该怎么做?我对 Django 很陌生。

标签: python django url redirect


【解决方案1】:

将这些添加到您的文件中。

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

【讨论】:

  • @joe 非常感谢您的回答。只是一次更正。 HttpResponseRedirect 是一个临时的方向。它提供了一个 http 状态代码 302。我想要一个状态代码为 301 的永久重定向。所以我只是将其更改为 HttpResponsePermanentRedirect。
猜你喜欢
  • 2018-10-21
  • 1970-01-01
  • 2016-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-06
  • 2013-12-09
相关资源
最近更新 更多