我正面临一个小问题,我无法透视它。
我有一个解析csv文件的命令行:
class Command(BaseCommand):
help = 'Import list of press article from .csv'
def handle(self, *args, **options):
activate('en') #without it the language will be wrong
ArticleFile = csv.reader(open(args[0]), delimiter=',')
global_article = ""
current_site = Site.objects.get_current()
is_new_source = []
for row in ArticleFile:
isIn = False
_country = ""
if row[0] != "Order":
if row[7] == "TRUE":
global_article = True
elif row[7] == "FALSE":
_country = Country.objects.get(name_ascii=row[6])
global_article = False
if row[5].endswith(' '):
row[5] = row[5][:-1]
for is_exist in is_new_source:
if is_exist.split(' ') == row[5].split(' '):
isIn = True
new_article = Article(
article_url=row[9],
global_regions=global_article,
title = row[8],
date_realization=datetime.strptime(row[4] + '-' + row[3] + '-' + row[2], '%Y-%m-%d').date(),
)
new_article.save()
if isIn == False:
is_new_source.append(row[5])
_source = ArticleSource.objects.create(name=row[5])
else:
_source = ArticleSource.objects.get(name=row[5])
new_article.sources.add(_source)
new_article.sites.add(current_site)
if _country != "":
new_article.article_country.add(_country)
我在我的管理员中有这条神奇的线条(例如源代码):
class ArticleSourceAdmin(VersionedPlaceholderAdminMixin,
FrontendEditableAdminMixin,
SortableAdminMixin):
list_display = ['__str__']
prepopulated_fields = {'slug': ('name',), }
admin.site.register(ArticleSource, ArticleSourceAdmin)
如果我手工拿到一篇文章,我可以看到slug在打字时会自动填充。 但是为了解析csv文件,使用命令行,slug将保持为空。
有什么想法吗?
非常感谢
答案 0 :(得分:4)
要自动设置slug
,您需要覆盖模型的save
方法。
由于您尚未发布模型,我将尝试用示例回答您的问题:
from django.utils.text import slugify
class MyModel(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(max_length=100)
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.name)
super(MyModel, self).save(*args, **kwargs)