简体   繁体   English

Django 1.6:创建子弹网址

[英]django 1.6: create slug url

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 我想把ug当作诊所的名字

Here is the models.py 这是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 这是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 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. 您需要将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)

Edit: 编辑:

If you have your url defined like @Norman8054 said: 如果您的网址定义如@ Norman8054所示:

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. 如果要确保slug字段是unic,则需要向save方法添加一些验证,或者使用模型的另一个字段进行slugify。 If you think that the slug field may change, you probably need to add the id of the object to the url as well. 如果您认为slug字段可能会更改,则可能还需要将对象的ID添加到url中。 But those are use-case based decisions. 但是这些都是基于用例的决策。

只是为了扩展cor的答案:在urls.py中使用命名组

url(r'^clinic/(?P<slug>\w+)/$', views.clinicProfile, name='clinicProfile'),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM