Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django通过命令填充类模型,在DB中工作,但不显示在页面上_Python_Django - Fatal编程技术网

Python Django通过命令填充类模型,在DB中工作,但不显示在页面上

Python Django通过命令填充类模型,在DB中工作,但不显示在页面上,python,django,Python,Django,所以,这个问题可能有点太具体了,我不确定,但我认为我在commandBase中填充类的方式遗漏了一些东西 而我现在得到的是: 在后台,在来源/文章列表中,一切都是正确的。但在我的页面中,不显示从.csv解析的文章 模型如下: class Article(ModelMeta, TranslatableModel): taints_cache = True """ Press article element, """ date_created = models.DateTimeField(auto

所以,这个问题可能有点太具体了,我不确定,但我认为我在commandBase中填充类的方式遗漏了一些东西

而我现在得到的是: 在后台,在来源/文章列表中,一切都是正确的。但在我的页面中,不显示从.csv解析的文章

模型如下:

class Article(ModelMeta, TranslatableModel):
taints_cache = True

"""
Press article element,
"""
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
date_realization = models.DateField(_('Realised in'),
                                     default=timezone.now)
image = FilerImageField(verbose_name=_('Featured image'), blank=True,
                             null=True,
                             on_delete=models.SET_NULL,
                             related_name='image_press_article',
                             help_text=_('Set if the article will be featured'))

sources = models.ManyToManyField(ArticleSource, verbose_name=_('Source'),
                                    blank=False, null=True, related_name='sources_press_article')

regions = models.ManyToManyField(Country, verbose_name=_('Country of the article'),
                                 blank=True, null=True,
                                 related_name='regions_press_article')

global_regions = models.BooleanField('Global', default=True)

featureArticle = models.BooleanField(_('Feature'), help_text=_('Feature this article'), default=False)

sites = models.ManyToManyField(Site, verbose_name=_('Sites'), blank=True,
                                                    null=True,
                                                    help_text=_('Select sites in which show the project.'))

article_url = models.CharField(_('Article Url'), max_length=310, blank=False,
                                   help_text=_('Use to link to the original source'))

countries_displayed_in = models.ManyToManyField(
    Country,
    verbose_name=_('Countries displayed in'),
    blank=True,
    null=True,
    related_name='displayed_in_press_article',
    help_text='Select the countries in which this project will be visible.'
    'If not selected, the project will be visible in all countries otherwise it will be'
    'visible only for users that are located in the countries selected')

translations = TranslatedFields(
    title=models.CharField(_('title'), max_length=510),
    slug=models.SlugField(_('slug'), blank=False, db_index=True, max_length=300),
    description=HTMLField(_('article description if featured'), default='', blank=True,
                          configuration='HTMLFIELD_CKEDITOR_SETTINGS_CONTENT'),

    meta_description=models.TextField(verbose_name=_('article meta description'),
                                      blank=True, default=''),
    meta_keywords=models.TextField(verbose_name=_('article meta keywords'),
                                   blank=True, default=''),
    meta_title=models.CharField(verbose_name=_('article meta title'),
                                help_text=_('used in title tag and social sharing'),
                                max_length=255,
                                blank=True, default=''),
    meta={'unique_together': (('language_code', 'slug'),)}
)

objects = ProjectManager()

_metadata = {
    'title': 'get_title',
    'description': 'get_description',
    'keywords': 'get_keywords',
    'locale': None,
    'image': 'get_image_full_url',
    'published_time': 'date_created ',
    'modified_time': 'date_modified',
    # Handle the get_absolute_url in the view to have access to the request
    # and so, to the current_app namespace instance
    # 'url': 'get_absolute_url',
}

def country(self):
    return "\n".join(([p.name for p in self.regions.all()]))

def source(self):
    return "\n".join([p.name for p in self.sources.all()])

def get_title(self):
    title = self.safe_translation_getter('meta_title', any_language=True)
    if not title:
        title = self.safe_translation_getter('title', any_language=True)
    return title.strip()

def get_keywords(self):
    return self.safe_translation_getter('meta_keywords').strip().split(',')

def get_description(self):
    description = self.safe_translation_getter('meta_description', any_language=True)
    if not description:
        description = self.safe_translation_getter('description', any_language=True)
    return escape(strip_tags(description)).strip()

def get_image_full_url(self):
    if self.image:
        return self.image.url
    return ''

class Meta:
    verbose_name = _('Press article')
    verbose_name_plural = _('Press articles')
    get_latest_by = 'date_realization'

def __str__(self):
    title = self.safe_translation_getter('title', any_language=True)
    return title if title is not None else '(not translated)'

def save(self, *args, **kwargs):
    if (self.article_url[:4] != "http") and (self.article_url[:5] != "https"):
        self.article_url = "https://" + self.article_url
    super(Article, self).save(*args, **kwargs)
    main_lang = self.get_current_language()
    for lang in self.get_available_languages():
        self.set_current_language(lang)
        if not self.slug and self.title:
            self.slug = slugify(self.title)
    self.set_current_language(main_lang)
    self.save_translations()

def get_slug(self):
    return self.safe_translation_getter(
        'slug',
        language_code=get_language(),
        any_language=False)
下面是我在django命令中添加新文章的步骤:

class Command(BaseCommand):
help = 'Import list of press article from .csv'

def handle(self, *args, **options):
    ArticleFile = csv.reader(open(args[0]), delimiter=',')
    global_article = ""
    _country = ""
    current_site = Site.objects.get_current()

    for row in ArticleFile:
        if row[0] != "Order":
            if row[7] == "TRUE":
                global_article = "True"
            elif row[7] == "FALSE":
                global_article = "False"

            _source = ArticleSource.objects.create(name=row[5])

            logging.info("\n\n URL: " + row[9] + "\n")
            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(),
                #sites=current_site,
            )

            new_article.save()
            new_article.sources.add(_source)
            new_article.sites.add(current_site)
            logging.info("\n\n title: " + new_article.title)
        if row[0] == "5":
            break
当我检查数据库并比较来自解析的文章和从后台添加的文章时,我注意到的唯一区别是语言

对于手动添加的,其为: “恩”,而对于那些来自.csv的,则是“恩我们”

所以这可能是个问题,但我不确定

即使是这样,我也不知道如何“强迫它”成为“en”而不是“en-us”

有人对此有线索吗? 我做得对吗?这是我第一次解析csv并用python/django填充外部模型


非常感谢。

哇,语言是个问题

我发现:

from django.utils.translation import activate
我只想补充一句:

class Command(BaseCommand):
help = 'Import list of press article from .csv'

def handle(self, *args, **options):
    activate('en')
到我的代码,现在一切都显示正确

顺便说一句,我仍然想知道我是否以正确的方式填充了我的类


请随意评论,我很想学习

哇,语言是个问题

我发现:

from django.utils.translation import activate
我只想补充一句:

class Command(BaseCommand):
help = 'Import list of press article from .csv'

def handle(self, *args, **options):
    activate('en')
到我的代码,现在一切都显示正确

顺便说一句,我仍然想知道我是否以正确的方式填充了我的类

请随意评论,我很想学习