Search code examples
pythondjangodjango-modelsslugify

Django Slugify with blank object field printing "none" in url


class Entry(models.Model):
    name = models.CharField(max_length=200, null=True, blank=True)
    city = models.CharField(max_length=200, null=True, blank=True)
    zip_code = models.ManyToManyField('EntryTwo', related_name="entries", blank=True)
    slug = models.SlugField(null=True, unique=True, max_length=300)
    id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
    
    def __str__(self):
        return self.name

    def get_absolute_url(self):
            return reverse("index", kwargs={"slug": self.slug})
    
    def save(self, *args, **kwargs):
    self.slug = slugify(f"{self.name}-{self.city}-{self.zip_code}")
    return super().save(*args, **kwargs)

Url is being returned as www.example.com/name-city-zip_code.

If an object has is missing a city, then url is returning: www.example.com/name-none-zip_code

How can I add an if statement in the F string in order to only display an object field if it is not None?

I tried the following but did not work:

self.slug = slugify(f"{self.name}-{self.city}-{self.zip_code}").replace("none","").

self.slug = slugify(f"{self.name}-{self.city}{% if self.zip_code %}-{self.zip_code}{% endif %}").

self.slug = slugify(f"{self.name}-{self.city}if self.zip_code:-{self.zip_code}").

self.slug = slugify(f"{self.name}-{self.city}if self.zip_code-{self.zip_code}").

Solution

  • you can do something like this and to make sure that the slug is unique i will add the id to the slug.

    class Entry(models.Model):
    
        ...................
    
        def save(self, *args, **kwargs):
            url_slug = ''
            name = self.name
            if name:
                url_slug += name +' '
    
            city = self.city
            if city:
                url_slug += city +' '
    
            id = self.id
            if id:
                url_slug += str(id)
    
            self.slug = slugify(url_slug.strip())
            return super().save(*args, **kwargs)