I have a clinic model and currently their links look like this
localhost:8000/clinic/1/
I want to make them look like this
localhost:8000/clinic/Nice-Medical-Clinic/
I want the slug to be the name of the clinic
Here is the models.py
class Clinic(models.Model):
name = models.CharField(max_length=500)
email = models.EmailField(blank = True, null = True)
address = map_fields.AddressField(max_length=200
website = models.CharField(max_length=50, blank = True, null = True)
submitted_on = models.DateTimeField(auto_now_add=True, null = True, blank = True)
def get_absolute_url(self):
from django.core.urlresolvers import reverse
return reverse('meddy1.views.clinicProfile', args=[str(self.id)])
Here is the views.py
def clinicProfile(request, slug, id):
clinic = Clinic.objects.get(id=id)
doctors = Doctor.objects.all().order_by('-netlikes')
d = getVariables()
d.update({'clinic': clinic, 'doctors': doctors, })
return render(request, 'meddy1/clinicprofile.html', d)
urls.py
url(r'^clinic/(?P<id>\d+)/$', views.clinicProfile, name='clinicProfile'),
You need to add a Slugfield or a CharField to your model, and populate it when ever you create or edit your model.
class Clinic(models.Model):
name = models.CharField(max_length=500)
...
slug = models.CharField(max_length=200)
def save(self, *args, **kwargs):
self.slug = slugify(self.name, instance=self)
super(Clinic, self).save(*args, **kwargs)
Edit:
If you have your url defined like @Norman8054 said:
url(r'^clinic/(?P<slug>\w+)/$', views.clinicProfile, name='clinicProfile'),
You can get the object in your views:
from django.shortcuts import get_object_or_404
def clinicProfile(request, slug):
clinic = Clinic.objects.get(slug=slug)
Those are the basic steps. If you want to be sure the slug field is unic, you need to add some validation to the save method, or slugify with another field of the model. If you think that the slug field may change, you probably need to add the id of the object to the url as well. But those are use-case based decisions.