James L.
James L.

Reputation: 1153

Create and redirect to slug urls in django

I have doctor profiles on my app and would like to create slug urls for all of them. So I've the following questions

  1. How do I create slug urls for the new doctors and as well as existing doctors in the database?

The url looks like this http://localhost:8000/docprofile/6/

and I want to make it like this http://localhost:8000/doctor/james-smith/

I want the slug to be based on the name of the doctor

  1. How do I do a permanent url redirection after implementing slug urls such that if a person goes to http://localhost:8000/docprofile/6/, the page is redirected to http://localhost:8000/doctor/james-smith/

Here is the 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'),

Upvotes: 0

Views: 1581

Answers (2)

torm
torm

Reputation: 1536

First question:

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

Second question:

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

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

Upvotes: 1

Greg
Greg

Reputation: 5588

You could just allow the user to input either id or doctor name

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

Upvotes: 0

Related Questions