我有一个诊所模型,目前他们的链接看起来像这样
localhost:8000/clinic/1/
我想让它们看起来像这样
localhost:8000/clinic/Nice-Medical-Clinic/
我希望slug成为诊所的名称
这是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)])
这是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'),
答案 0 :(得分:2)
您需要在模型中添加Slugfield或CharField,并在创建或编辑模型时填充它。
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)
修改强>
如果您的网址定义为@ Norman8054,则表示:
url(r'^clinic/(?P<slug>\w+)/$', views.clinicProfile, name='clinicProfile'),
您可以在视图中获取该对象:
from django.shortcuts import get_object_or_404
def clinicProfile(request, slug):
clinic = Clinic.objects.get(slug=slug)
这些是基本步骤。如果你想确定slug字段是unic,你需要在save方法中添加一些验证,或者用模型的另一个字段进行slugify。如果您认为slug字段可能会发生变化,您可能还需要将对象的id添加到url中。但这些都是基于用例的决策。
答案 1 :(得分:0)
只是为了扩展cor的答案:在你的urls.py中使用named group:
url(r'^clinic/(?P<slug>\w+)/$', views.clinicProfile, name='clinicProfile'),