Пример #1
0
    def readContent(self):
        with open(staticfiles_storage.path('content_api.json'),
                  encoding="utf-8") as f:
            data = json.load(f)

        for article in data['results']:
            if not Article.objects.filter(uuid=article['uuid']).exists():
                newArticle = Article()
                newArticle.authorByLine = article['byline']
                newArticle.body = article['body']
                newArticle.publishDate = article['publish_at'].split('T')[0]
                newArticle.headline = article['headline']
                newArticle.promo = article['promo']
                newArticle.disclosure = article['disclosure']
                newArticle.uuid = article['uuid']
                newArticle.slug = slugify(article['headline'])

                for img in article['images']:
                    if img['featured']:
                        newArticle.featuredImage = img['url']

                for ins in article['instruments']:
                    newArticle.save()
                    if Instrument.objects.filter(
                            instrumentId=ins['instrument_id']).exists():
                        newArticle.relatedInstruments.add(
                            Instrument.objects.get(
                                instrumentId=ins['instrument_id']))
                    else:
                        i = Instrument()
                        i.instrumentId = ins['instrument_id']
                        i.companyName = ins['company_name']
                        i.symbol = ins['symbol']
                        i.exchange = ins['exchange']
                        i.save()
                        newArticle.relatedInstruments.add(i)

                for tag in article['tags']:
                    newArticle.save()
                    if Tag.objects.filter(uuid=tag['uuid']).exists():
                        newArticle.tags.add(Tag.objects.get(uuid=tag['uuid']))
                    else:
                        t = Tag()
                        t.uuid = tag['uuid']
                        t.tagName = tag['name']
                        t.tagSlug = tag['slug']
                        t.tagTypeName = tag['tag_type']['name']
                        t.tagTypeSlug = tag['tag_type']['slug']
                        t.save()
                        newArticle.tags.add(t)
                newArticle.save()
            for tag in article['tags']:
                if self.first == '' and tag['slug'] == '10-promise':
                    self.first = Article.objects.get(uuid=article['uuid'])
Пример #2
0
def form(request, action, id='-1'):
    form = ArticleForm

    try:
        article = Article.objects.get(id=int(id))
        frm = form(
            initial={
                'author': article.author,
                'title': article.title,
                'body': article.body,
                'preview': article.preview,
                'tags_string': article.tags_string,
            })
    except Article.DoesNotExist:
        article = Article()
        frm = form()

    if request.method == 'POST':
        frm = form(request.POST)
        if frm.is_valid():
            cd = frm.cleaned_data
            article.author = cd['author']
            article.title = cd['title']
            article.body = cd['body']
            article.preview = cd['preview']

            article.tags_string = cd['tags_string']

            if action == 'add':
                article.created = datetime.now()

            article.modified = datetime.now()

            article.save()

            return HttpResponseRedirect('/articles')
            #return render_to_response('works/result.html', {'post': work })

    return direct_to_template(request, 'articles/form.html', {
        'form': frm,
        'article': article,
        'action': action
    })
Пример #3
0
def changeBD(request):
    items_news = []
    db = MySQLdb.connect(host="localhost",
                         user="******",
                         passwd="1(8Ik<7YgV",
                         db="giyyan_prasby",
                         charset='utf8')
    cursor = db.cursor()

    # запрос к БД
    sql = """SELECT author, title, preview, body, created FROM `articles_article_old`"""
    # выполняем запрос
    cursor.execute(sql)

    # получаем результат выполнения запроса
    data = cursor.fetchall()
    # перебираем записи
    for rec in data:
        # извлекаем данные из записей - в том же порядке, как и в SQL-запросе
        author, title, preview, body, created = rec
        # добавляем

        item = Article()
        item.author = author
        item.title = title
        item.title_by = title

        item.preview = preview
        item.preview_by = preview

        item.body = body
        item.body_by = body

        item.save()

        items_news.append(item)

    # закрываем соединение с БД
    db.close()

    return direct_to_template(request, 'tools/change.html',
                              {'items_news': items_news})
Пример #4
0
def form(request, action, id='-1'):
    form = ArticleForm

    try:
        article = Article.objects.get(id=int(id))
        frm = form(initial={
            'author': article.author,
            'title': article.title,
            'body': article.body,
            'preview': article.preview,
            'tags_string': article.tags_string,
        })
    except Article.DoesNotExist:
        article = Article()
        frm = form()

    if request.method == 'POST':
        frm = form(request.POST)
        if frm.is_valid():
            cd = frm.cleaned_data
            article.author = cd['author']
            article.title = cd['title']
            article.body = cd['body']
            article.preview = cd['preview']

            article.tags_string = cd['tags_string']

            if action == 'add':
                article.created = datetime.now()

            article.modified = datetime.now()

            article.save()

            return HttpResponseRedirect('/articles' )
            #return render_to_response('works/result.html', {'post': work })

    return direct_to_template(request, 'articles/form.html', {'form': frm, 'article': article, 'action': action})
Пример #5
0
def changeBD(request):
    items_news = []
    db = MySQLdb.connect(host="localhost", user="******", passwd="1(8Ik<7YgV", db="giyyan_prasby", charset="utf8")
    cursor = db.cursor()

    # запрос к БД
    sql = """SELECT author, title, preview, body, created FROM `articles_article_old`"""
    # выполняем запрос
    cursor.execute(sql)

    # получаем результат выполнения запроса
    data = cursor.fetchall()
    # перебираем записи
    for rec in data:
        # извлекаем данные из записей - в том же порядке, как и в SQL-запросе
        author, title, preview, body, created = rec
        # добавляем

        item = Article()
        item.author = author
        item.title = title
        item.title_by = title

        item.preview = preview
        item.preview_by = preview

        item.body = body
        item.body_by = body

        item.save()

        items_news.append(item)

    # закрываем соединение с БД
    db.close()

    return direct_to_template(request, "tools/change.html", {"items_news": items_news})
Пример #6
0
def step5(request, action_id, form_class=ActionStep5Form, template_name="actions/step5.html"):
    action = get_object_or_404(Action, pk=action_id)
    if not has_perm(request.user,'actions.add_action'): raise Http403
    
    if request.method == "POST":
        form = form_class(request.POST)
        
        if form.is_valid():
            add_article = form.cleaned_data['add_article']
            if add_article:
                # add an article
                from articles.models import Article
                from categories.models import Category
                from perms.object_perms import ObjectPermission
                from django.template.defaultfilters import slugify
                
                # article slug is a unique field, if the slug already exists,
                # what should we do? let append the action id to it to keep it unique
                slug = slugify(action.email.subject + '-' + str(action.id))
                try:
                    art = Article.objects.get(slug=slug)
                except Article.DoesNotExist:
                    art = Article()
                    art.headline = action.email.subject
                    art.slug = slug
                    art.summary = ""
                    art.body = action.email.body
                    art.sourct = request.user.get_full_name()
                    art.first_name = request.user.first_name
                    art.last_name = request.user.last_name
                    profile = request.user.get_profile()
                    art.phone = profile.phone
                    art.fax = profile.fax
                    art.email = profile.email
                    art.website = get_setting('site', 'global', 'siteurl')
                    art.release_dt = datetime.datetime.now()
                    
                    if action.member_only:
                        art.allow_anonymous_view = 1
                        art.allow_user_view = 1
                    art.allow_member_view = 1
                    art.allow_anonymous_edit = 0
                    art.allow_user_edit = 0
                    art.allow_member_edit = 0
                    art.status = 1
                    art.status_detail = 'active'
                    
                    art.creator = request.user
                    art.creator_username = request.user.username
                    art.owner = request.user
                    art.owner_username = request.user.username
                    art.save()
                
                    # user group - assign the permission to view this article
                    if action.group:
                        ObjectPermission.objects.assign_group(action.group, art)
                    
                    # update category
                    category = Category.objects.update(art, 'Newsletter', 'category')
                
                action.article = art
                
                action.save()
                
            #if action.group.members.count() < LIMIT:
            return HttpResponseRedirect(reverse('action.send', args=[action.id]))
            #else:
            #    # return to confirmation page    
            #    return HttpResponseRedirect(reverse('action.confirm', args=[action.id]))
    else:
        form = form_class()
    
    return render_to_response(template_name, {'form':form, 'action':action}, 
        context_instance=RequestContext(request))
Пример #7
0
                            path     = SimpleUploadedFile(path_str, data)
                            img      = ArticleImage(
                                image   = path,
                                caption = clean_text(photo['caption']),
                                byline  = photo['photographer'],
                                article = article
                            )
                            img.save()
                    status +=  '-- Imported images for new story %s<br>' % article.headline
            else:
                if article.headline != story['headline']:
                    article.headline  = story['headline']
                if article.summary  != story['summary']:
                    article.summary   = story['summary']
                if article.body     != story['body']:
                    article.body      = story['body']
                    status += 'updating story: %s <br>' % article.headline
                if article.dateline  != story['dateline']:
                    article.dateline = story['dateline']
                if article.overline  != story['overline']:
                    article.overline = story['overline']

                if article.id and story.has_key('images'):
                    img_count = 0
                    for photo_id, photo in story['images'].items():
                        dupe = False
                        filename = photo['source_url'].rsplit('/', 1)[1]
                        path_str = get_image_path(filename, pub_date)
                        shortname = path_str.split('.')[0] # get file name before the first period. Ex: /img/articles/mypic
                        #print shortname
                        #if shortname in current_images: