English 中文(简体)
如何在Django建立一个独特的贫民窟
原标题:How to create a unique slug in Django

I am trying to create a unique slug in Django so that I can access a post via a url like this: http://www.example.com/buy-a-new-bike_Boston-MA-02111_2

相关模式:

class ZipCode(models.Model):
    zipcode = models.CharField(max_length=5)
    city = models.CharField(max_length=64)
    statecode = models.CharField(max_length=32)

class Need(models.Model):
    title = models.CharField(max_length=50)
    us_zip = models.CharField(max_length=5)
    slug = ?????

    def get_city():
        zip = ZipCode.objects.get(zipcode=self.us_zip)
        city = "%s, %s %s" % (zip.city, zip.statecode, zip.zipcode)
        return city

样本ZipCode记录:

  • zipcode = "02111"
  • city = "Boston"
  • statecode = "MA"

需求记录样本:

  • title = "buy a new bike"
  • us_zip = "02111"
  • slug = "buy-a-new-bike_Boston-MA-02111_2" (desired)

如何创造这一独特lu? 其组成如下:

  • Need.title + "_" + Need.get_city() + "_" + an optional incrementing integer to make it unique. All spaces should be replaced with "-".

注:我上文所希望的概要假设,“Boston-MA-02111”的 s鱼已经存在,这是它为了使其独一无二而附加的“_2”。

我曾尝试过暴风雨,但似乎只能从田地或田径修建独一无二的lu。 我需要在所有权和城市之间的“城市”功能以及“_”连接器上通过。 任何人都解决这个问题,愿意分享?

谢谢!

<>>>>>

我已经为其“统一调查”现场使用过 d沟,因此,如果它也能为其“自动调查”现场使用的话,那将是ice!

最佳回答

我利用这个网站snippet,生成独一的 s,而我的典型节省方法如下:

贫民窟为Django Slug 油田,有空白点为True,但以节省的方式强制实行 s。

典型的“需要”模式可考虑如下:

def save(self, **kwargs):
    slug_str = "%s %s" % (self.title, self.us_zip) 
    unique_slugify(self, slug_str) 
    super(Need, self).save(**kwargs)

这将产生lu,如购买-a-new-bike_Boston-MA-02111, 购买-a-new-bike_Boston-MA-02111-1等。 产出可能没有什么不同,但你总是可以满足你的需要。

问题回答

我的手法很少:

def save(self, *args, **kwargs):
    strtime = "".join(str(time()).split("."))
    string = "%s-%s" % (strtime[7:], self.title)
    self.slug = slugify(string)
    super(Need, self).save()

如果你想用自己的遗嘱来为你们做,那么,这里就是这样。

https://github.com/un33k/django-uuslug”rel=“noreferer”>https://github.com/un33k/django-uuslug

UUSlug = (``U``nique + ``U``code Slug)


Unicode Test Example
=====================
from uuslug import uuslug as slugify

s = "This is a test ---"
r = slugify(s)
self.assertEquals(r, "this-is-a-test")

s =  C est déjà l été. 
r = slugify(s)
self.assertEquals(r, "c-est-deja-l-ete")

s =  Nín hǎo. Wǒ shì zhōng guó rén 
r = slugify(s)
self.assertEquals(r, "nin-hao-wo-shi-zhong-guo-ren")

s =  影師嗎 
r = slugify(s)
self.assertEquals(r, "ying-shi-ma")


Uniqueness Test Example
=======================
Override your objects save method with something like this (models.py)

from django.db import models
from uuslug import uuslug as slugify

class CoolSlug(models.Model):
    name = models.CharField(max_length=100)
    slug = models.CharField(max_length=200)

    def __unicode__(self):
        return self.name

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name, instance=self)
        super(CoolSlug, self).save(*args, **kwargs)

Test:
=====

name = "john"
c = CoolSlug.objects.create(name=name)
c.save()
self.assertEquals(c.slug, name) # slug = "john"

c1 = CoolSlug.objects.create(name=name)
c1.save()
self.assertEquals(c1.slug, name+"-1") # slug = "john-1"

这里是我使用的双重职能。 页: 1 如果确实存在 t,则会继续试图在发现独一无二的str断时标出4位数。

import string
from django.utils.crypto import get_random_string

def unique_slugify(instance, slug):
    model = instance.__class__
    unique_slug = slug
    while model.objects.filter(slug=unique_slug).exists():
        unique_slug = slug + get_random_string(length=4)
    return unique_slug

我通常使用该模型<代码>save方法。

class YourModel(models.Model):
    slug = models.SlugField()
    title = models.CharField()

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = unique_slugify(self, slugify(self.title))
        super().save(*args, **kwargs)

This is the simple and small code i am using for generating unique slug, you only need one field to create your unique slug field

from random import randint

def save(self, *args, **kwargs):
    if Post.objects.filter(title=self.title).exists():
        extra = str(randint(1, 10000))
        self.slug = slugify(self.title) + "-" + extra
    else:
        self.slug = slugify(self.title)
    super(Post, self).save(*args, **kwargs)

我希望你们也这样做。

这是一种简单的实施,它产生于所有权上的lu,它取决于其他氮:

from django.template.defaultfilters import slugify

class Article(models.Model):
    ...
    def save(self, **kwargs):
        if not self.slug:
            slug = slugify(self.title)
            while True:
                try:
                    article = Article.objects.get(slug=slug)
                    if article == self:
                        self.slug = slug
                        break
                    else:
                        slug = slug +  - 
                except:
                    self.slug = slug
                    break

        super(Article, self).save()

Django是一个Slug Field模型领域,使你更容易获得这一服务。 这里的“博客”中的例子

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField(blank=True)

    slug = models.SlugField(unique=True)

    @models.permalink
    def get_absolute_url(self):
        return  blog:post , (self.slug,)

请注意,我们已确定了独一无二的= 真正地看着我们的工作领域——在这个项目中,我们将用自己的力量来审视职位,因此,我们必须确保这些职位是独特的。 在这方面,我们的发言提出了我们的看法。 或许希望这样做:

from .models import Post

def post(request, slug):
    post = get_object_or_404(Post, slug=slug)

    return render(request,  blog/post.html , {
         post : post,
    })

from django.utils.text import slugify Helps a lot and has quite clear Concepts. Here one example on How to auto-generate slug by using from django.utils.text import slugify

残割。 y

from django.utils.text import slugify
import random
import string

# Random string generator
def random_string_generator(size=10, chars=string.ascii_lowercase + string.digits):
    return   .join(random.choice(chars) for _ in range(size))

# Unique Slug Generator 
def unique_slug_generator(instance, new_slug=None):
    """
    It assumes your instance has a model with a slug field and a title character (char) field.
    """
    if new_slug is not None:
        slug = new_slug  
    else:
        slug = slugify(instance.title)  

    Klass = instance.__class__

    qs_exists = Klass.objects.filter(slug=slug).exists()

    if qs_exists:
        new_slug = "{slug}-{randstr}".format(slug=slug, randstr=random_string_generator(size=4))
        return unique_slug_generator(instance, new_slug=new_slug)
    return slug

模式。 y

from django.db.models.signals import pre_save # Signals
# import the unique_slug_generator from .残割。 y 
from .utils import unique_slug_generator

class Product(models.Model):
    title  = models.CharField(max_length=120)
    # set blank to True
    slug  = models.SlugField(blank=True, unique=True)

def product_pre_save_receiver(sender, instance, *args, **kwargs):
    if not instance.slug:
        instance.slug = unique_slug_generator(instance)


pre_save.connect(product_pre_save_receiver, sender=Product)

Django文件解释了Django.utils.text import slugification,以便自动产生 s。 详情见

在实施该守则之后,在创造产品时,你可以留下 s块的现场空白,而这种空白将进一步得到该产品的汽车产生的lu,而这一产品在这种情况下是独特的。

class Training(models.Model):
    title = models.CharField(max_length=250)
    text = models.TextField()
    created_date = models.DateTimeField(
    auto_now_add=True, editable=False, )
    slug = models.SlugField(unique=True, editable=False, max_length=250)

    def __unicode__(self):
       return self.title

    def get_unique_slug(id,title,obj):
      slug = slugify(title.replace( ı ,  i ))
      unique_slug = slug
      counter = 1
      while obj.filter(slug=unique_slug).exists():
         if(obj.filter(slug=unique_slug).values( id )[0][ id ]==id):
             break
         unique_slug =  {}-{} .format(slug, counter)
         counter += 1
      return unique_slug.  

    def save(self, *args, **kwargs):
       self.slug =self.get_unique_slug(self.id,self.title,Training.objects)
       return super(Training, self).save(*args, **kwargs)
 def get_slug(self):
    slug = slugify(self.title.replace("ı", "i"))
    unique = slug
    number = 2

    while Model.objects.filter(slug=unique).exists():
        unique = "{}-{}".format(slug, number)
        number += 1
    return unique

我的最佳解决办法:

def get_slug(self):
    slug = slugify(self.title)
    unique_slug = slug

    number = 1
    while Recipe.objects.filter(slug=unique_slug).exists():
        unique_slug = f {slug}-{number} 
        number += 1

    return unique_slug

def save(self, *args, **kwargs):
    if not self.slug:
        self.slug = self.get_slug()
    return super().save(*args, **kwargs)

这部法典可以产生这样的诱惑:

  • string-slug
  • string-slug-1 (if previous alredy exists)
  • string-slug-2 (if previous alredy exists)
  • and so on...
class Need(models.Model):
    title = models.CharField(max_length=50)
    us_zip = models.CharField(max_length=5)
    slug = models.SlugField(unique=True)

    def save(self, **kwargs):
        slug_str = "%s %s" % (self.title, self.us_zip) 
        super(Need, self).save()

对我来说,这预示着:

class Parcel(models.Model):
    title = models.CharField(max_length-255)
    slug = models.SlugField(unique=True, max_length=255)
    weight = models.IntegerField()
    description = models.CharField(max_length=255)
    destination = models.CharField(max_length=255)
    origin = models.CharField(max_length=255)

    def __str__(self):
        return self.description

    def save(self, *args, **kwargs):
        if not self.slug:
            t_slug = slugify(self.title)
            startpoint = 1
            unique_slug = t_slug
            while Parcel.objects.filter(slug=unique_slug).exists():
                unique_slug =  {} {} .format(t_slug, origin)
                origin += 1
            self.slug = unique_slug
        super().save(*args, **kwargs)




相关问题
How to get two random records with Django

How do I get two distinct random records using Django? I ve seen questions about how to get one but I need to get two random records and they must differ.

Moving (very old) Zope/Plone Site to Django

I am ask to move data from a (now offline) site driven by Plone to a new Django site. These are the version informations I have: Zope Version (unreleased version, python 2.1.3 ) Python Version 2.1....

Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

Flexible pagination in Django

I d like to implement pagination such that I can allow the user to choose the number of records per page such as 10, 25, 50 etc. How should I go about this? Is there an app I can add onto my project ...

is it convenient to urlencode all next parameters? - django

While writing code, it is pretty common to request a page with an appended "next" query string argument. For instance, in the following template code next points back to the page the user is on: &...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

热门标签