在django中创建并重定向到slug url

时间:2014-12-28 08:35:52

标签: python django url redirect slug

我的应用程序上有医生个人资料,并希望为所有人创建slug网址。所以我提出了以下问题

  1. 如何为新医生以及数据库中的现有医生创建slug网址?
  2. 网址看起来像http://localhost:8000/docprofile/6/

    我希望这样做http://localhost:8000/doctor/james-smith/

    我希望slu is基于医生的名字

    1. 如何在实施slug网址后执行永久网址重定向,以便当某人访问http://localhost:8000/docprofile/6/时,该网页会重定向到http://localhost:8000/doctor/james-smith/
    2. 这是models.py

      class Doctor(models.Model):
          name = models.CharField(max_length=1300)
          specialization = models.ForeignKey(Specialization)
      
          def __unicode__(self):
            return u"%s %s" % (self.name, self.specialization)
      
          def get_absolute_url(self):
              from django.core.urlresolvers import reverse
              return reverse('kk1.views.showDocProfile', args=[str(self.id)])
      

      views.py

      def showDocProfile(request, id):
          doctor = Doctor.objects.get(id=id)
          clinic = Clinic.objects.get(id=doctor.clinic.id)
      
          d = getVariables(request,dictionary={'page_name': doctor.name +" "+ doctor.specialization.name +" -})
      
      
          d.update({'doctor': doctor, 'clinic': clinic,'form': form })
          return render(request, 'kk1/docprofile.html', d)
      

      urls.py

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

2 个答案:

答案 0 :(得分:1)

第一个问题:

url(r'^doctor/(?P<name>\w+)/$', views.showDocProfileByName),

第二个问题:

def showDocProfileById(request, id):
    doctor = Doctor.objects.get(id=id)
    name = doctor.name.replace(' ', '-')

    HttpResponseRedirect(reverse('project.views.showDocProfileByName', args=(name)))

答案 1 :(得分:0)

您可以让用户输入身份证或医生姓名

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