I am trying to create a blog website.but when i try to import generate_unique_slug from .slugs django throws an error No module named 'blog.slugs'. can you help me fix this?
models.py
from django.db import models
from user_profile.models import User
from django.utils.text import slugify
from ckeditor.fields import RichTextField
from .slugs import generate_unique_slug
# Create your models here.
class Category(models.Model):
title = models.CharField(max_length=150, unique=True)
slug = models.SlugField(null=True, blank=True)
created_date = models.DateField(auto_now_add=True)
def __str__(self) -> str:
return self.title
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super().save(*args, **kwargs)
class Blog(models.Model):
user = models.ForeignKey(
User,
related_name='user_blogs',
on_delete=models.CASCADE
)
category = models.ForeignKey(
Category,
related_name='category_blogs',
on_delete=models.CASCADE
)
title = models.CharField(
max_length=250
)
slug = models.SlugField(null=True, blank=True)
banner = models.ImageField(upload_to='blog_banners')
description = RichTextField()
created_date = models.DateField(auto_now_add=True)
def __str__(self) -> str:
return self.title
def save(self, *args, **kwargs):
updating = self.pk is not None
if updating:
self.slug = generate_unique_slug(self, self.title, update=True)
super().save(*args, **kwargs)
else:
self.slug = generate_unique_slug(self, self.title)
super().save(*args, **kwargs)
admin.py
from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(Category)
admin.site.register(Blog)
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
'user_profile',
'ckeditor',
]
when i delete this code from .slugs import generate_unique_slug
the error disappears.maybe I'm importing it wrong?I will be very grateful if you help to solve the problem
CodePudding user response:
In this line
from .slugs import generate_unique_slug
You are trying to import generate_unique_slug from you project file, and as you commented you don’t have this file in your project
The solution is you should write this function generate_unique_slug you can put it in file call slugs.py and it will work, or write this function inside model and delete this line
Note: this function should contain the logic for generate a unique slug depends on what you want