Reputation: 21
Django slug field does not work for any other language except English. I want to work with Bengali language here is the code
class Post(models.Model):
title = models.CharField(max_length=140)
category = models.ForeignKey(Category, on_delete=models.DO_NOTHING)
content = RichTextField(default="")
image = models.ImageField(upload_to="media/post")
url = models.SlugField(unique=True, max_length=250, null=True, blank=True)
likes = models.IntegerField(default=0)
created_date = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
def __str__(self):
return f"{self.title}"
def save(self, *args, **kwargs): # new
if not self.url:
slug_str = f"{self.title}-{datetime.datetime.now()}"
self.url = slugify(slug_str)
return super().save(*args, **kwargs)
Upvotes: 0
Views: 506
Reputation: 101
from PIL import Image
from io import BytesIO
class Post(models.Model):
title = models.CharField(max_length=140)
category = models.ForeignKey(Category, on_delete=models.DO_NOTHING)
content = RichTextField(default="")
image = models.ImageField(upload_to="media/post")
url = url = models.SlugField(allow_unicode=True, unique=True, max_length=150, null=True, blank=True)
likes = models.IntegerField(default=0)
created_date = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
def __str__(self):
return f"{self.title}"
def save(self, *args, **kwargs):
if not self.url:
slug_str = f"{self.title}"
self.url = self.title.replace(" ", "-").replace(",", "")
return super().save(*args, **kwargs)
if self.image:
img = Image.open(self.image)
output = BytesIO()
img.convert('RGB').save(output, format='webp', maxsize=(800, 800))
self.image = InMemoryUploadedFile(output,'ImageField', "%s.webp" %self.image.name.split('.')[0], 'media/post', output.getvalue(), None)
super(Post, self).save(*args, **kwargs)
Upvotes: 0
Reputation: 180
Here is an example how I've done this in one of my project.
Title : স্পেনের মাদ্রিদে বাংলা প্রেসক্লাবের দ্বিবার্ষিক সম্মেলন
You can use SlugField and allow unicode but you will get the slug: সপনর-মদরদ-বল-পরসকলবর-দববরষক-সমমলন
Let's solve this issue:
slug = models.CharField(
max_length=200,
unique=True, blank=True, null=True, editable=True
)
def save(self,*args, **kwargs):
if not self.slug:
self.slug = self.title.replace(" ", "-").replace(",", "")
return super(BanglaModel, self).save(*args, **kwargs)
Output slug: স্পেনের-মাদ্রিদে-বাংলা-প্রেসক্লাবের-দ্বিবার্ষিক-সম্মেলন
Upvotes: 0
Reputation: 32294
Pass allow_unicode=True to your SlugField
to accept unicode chars
class Post(models.Model):
...
url = models.SlugField(allow_unicode=True, unique=True, max_length=250, null=True, blank=True)
Then when you generate the slug you need to pass the same parameter to django.utils.text.slugify
def save(self, *args, **kwargs): # new
if not self.url:
slug_str = f"{self.title}-{datetime.datetime.now()}"
self.url = slugify(slug_str, allow_unicode=True)
return super().save(*args, **kwargs)
Upvotes: 2