Esempio n. 1
0
def visit_corporation_topics(request, gurl_number):
    corporation = Corporation.objects(url_number=gurl_number).get()
    if request.method == "POST":
        form = NewTopicForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data['title']
            content = form.cleaned_data['content']
            topic = Topic(title=title)
            turl_number = len(Topic.objects) + 1
            topic.url_number = turl_number
            topic.content = content
            topic.creat_time = datetime.datetime.now()
            topic.is_active = True
            topic.is_locked = False
            topic.is_top = False
            topic.clicks = 0
            topic.update_time = datetime.datetime.now()
            topic.update_author = request.user
            sccard = S_C_Card.objects(user=request.user,
                                      corporation=corporation).get()
            topic.creator = sccard
            topic.save()
            return HttpResponseRedirect('/corporation/' + str(gurl_number) +
                                        '/topic/' + str(turl_number) + '/')

    else:
        form = NewTopicForm()
        return render_to_response('corporation/corporation_topics.html', {
            'form': form,
            'corporation': corporation,
            'STATIC_URL': STATIC_URL,
            'current_user': request.user
        },
                                  context_instance=RequestContext(request))
Esempio n. 2
0
    def post(request, lang, topic_id):
        if lang == 'ja':
            topic_model = Topic()
        else:
            topic_model = TopicEn()

        topic = topic_model.get_by_id(topic_id)
        if topic is None:
            return JsonResponse({
                'status': 503, 'message': '投稿が存在しません'}, status=503)

        form = NewForm(request.POST)
        if form.errors:
            messages.add_message(request, messages.INFO,
                                 dict(form.errors.items()))
        if form.is_valid():
            try:
                topic_model.new_change(
                    form.cleaned_data.get('new'), topic_id)
            except:
                return JsonResponse({
                    'status': 500, 'message': 'Not Change'}, status=500)

        else:
            return JsonResponse({
                'status': 500, 'message': get_error_message(request)},
                status=500)

        return JsonResponse({
            'status': 200, 'message': 'Changed'},
            status=200)
Esempio n. 3
0
def topic_add_edit(request, polity_id, topic_id=None):
    try:
        polity = Polity.objects.get(id=polity_id, officers=request.user)
    except Polity.DoesNotExist:
        raise PermissionDenied()

    if topic_id:
        topic = get_object_or_404(Topic, id=topic_id, polity_id=polity_id)
    else:
        topic = Topic(polity=polity)

    if request.method == 'POST':
        form = TopicForm(request.POST, instance=topic)
        if form.is_valid():
            topic = form.save()
            return redirect(reverse('topic', args=(polity_id, topic.id)))
    else:
        form = TopicForm(instance=topic)

    ctx = {
        'polity': polity,
        'topic': topic,
        'form': form,
    }
    return render(request, 'topic/topic_form.html', ctx)
Esempio n. 4
0
    def get(request, lang, topic_id):

        if lang == 'ja':
            topic_model = Topic()
        else:
            topic_model = TopicEn()

        topic = topic_model.get_by_id(topic_id)
        if topic is None:
            raise Http404

        title = topic.title
        if lang == 'ja':
            use_videos = topic.video_set.all().order_by('video_topic.id')
            use_images = topic.images.all().order_by('topic_images.id')
        else:
            use_videos = topic.videoen_set.all().order_by('video_en_topic.id')
            use_images = topic.images.all().order_by('topic_en_images.id')

        return TemplateResponse(request, 'topic.html', {
            'title': title + ' | トピックス | FEED App 管理',
            'topic': topic,
            'use_videos': use_videos,
            'use_images': use_images,
            'error_messages': {},
            'form_data': {},
            'lang': lang,
            'post_types': [
                {'name': 'トピック', 'val': 'topic'},
                {'name': 'イベント', 'val': 'event'},
            ]
        })
Esempio n. 5
0
    def get(request, lang, paged=1):

        search = request.GET.get('search', '')

        if lang == 'ja':
            topic_model = Topic()
        else:
            topic_model = TopicEn()

        if search != '':
            total = topic_model.get_topic_search_all(search).count()
        else:
            total = topic_model.get_all().count()

        pagination = Pagination(
            page=paged, per_page=10, total=total, query=search,
            slug='/{}/admin/topics/page/'.format(lang))

        if search != '':
            topics = topic_model.get_topic_search_all(search)[
                pagination.offset:pagination.offset + pagination.per_page]
        else:
            topics = topic_model.get_all()[
                pagination.offset:pagination.offset + pagination.per_page]

        return TemplateResponse(request, 'topics.html', {
            'title': 'トピックス | FEED App 管理',
            'topics': topics,
            'information': pagination.information(),
            'pagination': pagination,
            'lang': lang,
            'search': search,
        })
Esempio n. 6
0
    def get(_, lang, image_id):

        delete_flag = True

        image_model = Image()
        category_model = Category()

        if lang == 'ja':
            topic_model = Topic()
            introduction_model = Introduction()
        else:
            topic_model = TopicEn()
            introduction_model = IntroductionEn()

        try:
            image = image_model.get_by_image_id(image_id)

            topic_use_flag, topic_use_posts = topic_model.is_use_image(
                image.image_url, image.id)

            if topic_use_flag is True:
                delete_flag = False

            introduction_use_flag, introduction_use_posts = \
                introduction_model.is_use_image(image.image_url)

            if introduction_use_flag is True:
                delete_flag = False

            category_use_flag, category_use_posts = category_model.is_use_image(
                image.image_url)

            if category_use_flag is True:
                delete_flag = False

            use_posts = (
                topic_use_posts +
                category_use_posts +
                introduction_use_posts
            )

            def get_unique_list(seq):
                seen = []
                return [x for x in seq if x not in seen and not seen.append(x)]

            use_posts = get_unique_list(use_posts)

            return JsonResponse({
                'status': 200,
                'delete_flag': delete_flag,
                'use_posts': use_posts,
            }, status=200)

        except Exception as e:
            return JsonResponse({
                'status': 500,
                'message': 'Exception Error ' + str(e)
            }, status=500)
Esempio n. 7
0
    def get(request, lang, paged=1):
        try:

            value = request.GET.get('value')

            if lang == 'ja':
                topic_model = Topic()
            else:
                topic_model = TopicEn()

            if value != '':
                total = topic_model.get_topic_search_all(value).count()
            else:
                total = topic_model.get_all().count()

            pagination = Pagination(
                page=paged, per_page=10, total=total, slug='')

            if value != '':
                topics = topic_model.get_topic_search_all(value)[
                     pagination.offset:pagination.offset + pagination.per_page]
            else:
                topics = topic_model.get_all()[
                     pagination.offset:pagination.offset + pagination.per_page]

            if lang == 'ja':
                res = TopicsSerializer(topics, many=True).data
            else:
                res = TopicsEnSerializer(topics, many=True).data

            return JsonResponse({
                'total': pagination.pages,
                'paged': paged,
                'topics': res,
            }, safe=False)

        except Exception as e:
            return JsonResponse({
                'status': 500,
                'message': 'Exception Error ' + str(e)
            }, status=500)
Esempio n. 8
0
    def get(request, lang):
        if lang == 'ja':
            introduction_model = Introduction()
            video_model = Video()
            topic_model = Topic()
        else:
            introduction_model = IntroductionEn()
            video_model = VideoEn()
            topic_model = TopicEn()

        introductions = introduction_model.get_all()[:3]
        videos = video_model.get_all()[:3]
        topics = topic_model.get_all()[:3]

        return TemplateResponse(request, 'top.html', {
            'title': 'FEED App 管理',
            'introductions': introductions,
            'videos': videos,
            'topics': topics,
            'lang': lang,
        })
Esempio n. 9
0
    def post(_, lang, topic_id):

        sid = transaction.savepoint()
        if lang == 'ja':
            topic_model = Topic()
            video_model = Video()
        else:
            topic_model = TopicEn()
            video_model = VideoEn()

        try:
            video_model.remove_video_from_topic(topic_id)
            topic_model.delete_topic(topic_id)
            topic_model.remove_image(topic_id)
            transaction.savepoint_commit(sid)

        except:

            transaction.savepoint_rollback(sid)
            pass

        return HttpResponseRedirect('/{}/admin/topics'.format(lang))
Esempio n. 10
0
    def handle(self, *args, **options):
        now = datetime.now()

        if not options.get('full'):
            print
            print 'NOTE: Creating small test data set, use --full for MOAR DATA.'
            print

        reset = False
        if options.get('reset'):
            yn = raw_input(
                'Are you sure you want to delete precious data? [y/N] ')
            if yn.strip().lower() == 'y':
                reset = True
            else:
                return

        create_all = not (options.get('users', False) or options.get(
            'topics', False) or options.get('elections', False)
                          or options.get('documents', False))

        userlist = [('a', '*****@*****.**', 'Alpha'),
                    ('b', '*****@*****.**', 'Beta'),
                    ('c', '*****@*****.**', 'Foo'),
                    ('d', '*****@*****.**', 'Baz')]
        userlist += [('user%s' % i, '*****@*****.**' % i, 'User %s' % i)
                     for i in range(0, 1110)]
        serial_ssn = 0
        if options.get('users') or create_all:
            if not options.get('full'):
                userlist = userlist[:20]
            print 'Generating %d users ...' % len(userlist)
            users = {}
            if reset:
                User.objects.all().delete()
            for u, email, name in userlist:
                try:
                    if len(u) == 1:
                        users[u] = User.objects.create_user(u, password=u)
                        users[u].is_staff = True
                        users[u].is_superuser = True
                        print '   * Creating user "%s" with password "%s"' % (
                            u, u)
                    else:
                        users[u] = User.objects.create_user(u)
                    users[u].email = email
                    users[u].save()
                    UserProfile(
                        user=users[u],
                        verified_ssn='%10.10d' % serial_ssn,
                        joined_org=now -
                        timedelta(hours=random.randint(0, 24 * 5))).save()
                    serial_ssn += 1
                except IntegrityError:
                    # User already exists
                    users[u] = User.objects.get(email=email)

        print 'Generating/updating 4 polities of varying sizes ...'
        pollist = [('d', 'The Big Polity', 'abc', 1000),
                   ('c', 'The Medium Polity', 'abc', 100),
                   ('b', 'The Small Polity', 'ab', 10),
                   ('a', 'The Dinky Polity', 'a', 1)]
        if not options.get('full'):
            pollist = pollist[2:]
        topiclist = []
        for t1 in ADJECTIVES:
            for t2 in THINGS:
                for t3 in ACTIONS:
                    topiclist.append('%s %s %s' % (t1, t2, t3))
        polities = {}
        documents = {}
        for u, name, members, size in pollist:
            print '   + %s (size=%d)' % (name, size)
            usr = User.objects.get(username=u)
            try:
                p = Polity.objects.get(name=name)
                new = False
            except:
                p = Polity(name=name,
                           slug=name.lower().replace(' ', '-'),
                           description='A polity with about %d things' % size)
                p.created = now - timedelta(hours=random.randint(0, 24 * 5))
                p.created_by = usr
                p.modified_by = usr
                p.save()
                PolityRuleset(polity=p,
                              name='Silly rules',
                              issue_majority=50,
                              issue_discussion_time=24 * 3600,
                              issue_proposal_time=24 * 3600,
                              issue_vote_time=24 * 3600).save()
                new = True
            polities[u] = (p, size)

            if new or options.get('topics') or create_all:
                n = 1 + min(size // 5, len(topiclist))
                print '       - Creating %d topics' % n
                if reset:
                    Topic.objects.filter(polity=p).delete()
                for topic in random.sample(topiclist, n):
                    Topic(name=topic, polity=p, created_by=usr).save()

            if new or options.get('users') or create_all:
                print '       - Adding ~%d users' % size
                for m in set([m for m in members] +
                             random.sample(users.keys(), size)):
                    try:
                        # User d is a member of no polities
                        if m != 'd':
                            p.members.add(users[m])
                    except:
                        pass

            if options.get('elections') or create_all:
                # Create 3 elections per polity:
                #    one soliciting candidates, one voting, one finished
                print '       - Creating 3 elections'
                if reset:
                    Election.objects.filter(polity=p).delete()
                for dc, dv in ((1, 2), (-1, 1), (-2, -1)):
                    e = Election(name="%s Manager" % random.choice(THINGS),
                                 polity=p,
                                 voting_system='schulze',
                                 deadline_candidacy=now + timedelta(days=dc),
                                 deadline_votes=now + timedelta(days=dv),
                                 deadline_joined_org=now + timedelta(days=dv))
                    e.save()

                    if (dc < 0) or (dv < 0):
                        candidatec = min(p.members.count(), 15)
                        voterc = 0
                    else:
                        candidatec = min(p.members.count(), 5)
                        voterc = min(p.members.count(), 5)

                    candidates = []
                    for cand in random.sample(p.members.all(), candidatec):
                        c = Candidate(election=e, user=cand)
                        c.save()
                        candidates.append(c)
                    for voter in random.sample(p.members.all(), voterc):
                        random.shuffle(candidates)
                        for rank, cand in enumerate(candidates):
                            ElectionVote(election=e,
                                         user=voter,
                                         candidate=cand,
                                         value=rank).save()

                    if (dv < 0) and voterc and candidatec:
                        try:
                            e.process()
                        except:
                            traceback.print_exc()
                            print 'Votes cast on %s: %s' % (
                                e, ElectionVote.objects.filter(
                                    election=e).count())

            if new or options.get('documents') or create_all:
                # We create a list of authors biased towards the first
                # users created, so some users will have lots of documents
                # and others will have less.
                ul = [username for username, e, n in userlist]
                aw = [(m.username, max(20 - ul.index(m.username), 1))
                      for m in p.members.all()]
                authors = [a for a, w in aw for i in range(0, w)]

                # Get a list of topics...
                topics = Topic.objects.filter(polity=p)

                print '       - Creating %d documents' % size
                if reset:
                    Document.objects.filter(polity=p).delete()
                for docn in range(0, size):
                    topic = random.choice(topics)
                    subject = '%s %s with %s' % (random.choice(ACTACTS),
                                                 topic.name,
                                                 random.choice(THINGS) + 's')
                    author = User.objects.get(username=random.choice(authors))
                    doc = Document(name=subject, user=author, polity=p)
                    doc.save()
                    doc.created = now - timedelta(
                        hours=random.randint(0, 24 * 3))
                    doc.save()

                    documents[doc.id] = (topic, doc)
                    text = subject
                    for version in range(0, random.randint(1, 3)):
                        text = '%s\n%s' % (text, text)
                        docc = DocumentContent(document=doc,
                                               user=author,
                                               text=text)
                        docc.status = 'proposed'
                        docc.order = version
                        docc.save()

        if options.get('documents') or create_all:
            # Put max(3, 10%) of all the documents up for election
            howmany = min(max(3, len(documents) // 10), len(documents))
            print 'Creating issues for %d documents.' % howmany
            j = 1
            for dk in random.sample(documents.keys(), howmany):
                topic, doc = documents[dk]
                i = Issue(
                    name=doc.name,
                    polity=doc.polity,
                    created_by=doc.user,
                    issue_num=j,
                    issue_year=2018,
                    ruleset=PolityRuleset.objects.filter(polity=doc.polity)[0],
                    majority_percentage=50,
                    documentcontent=doc.preferred_version())
                i.save()
                i.created = doc.created
                i.apply_ruleset(now=doc.created)
                i.save()
                i.topics.add(topic)
                j += 1
Esempio n. 11
0
# -*- coding: utf-8 -*-
__author__ = 'bobby'
import sys
import os

pwd = os.path.dirname(os.path.realpath(__file__))
sys.path.append(pwd + "../")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "v2ex.settings")

import django
django.setup()

from topic.models import Topic

from db_tools.data.topic_data import row_data

for tips_detail in row_data:
    tips = Topic()
    tips.title = tips_detail["title"]
    tips.topic_sn = tips_detail["tips_sn"]
    tips.click_num = tips_detail["click_num"]
    tips.like_num = tips_detail["like_num"]
    tips.dislike_num = tips_detail["dislike_num"]
    tips.title = tips_detail["title"]
    tips.content = tips_detail["content"]
    tips.category_id = tips_detail["category"]
    tips.author_id = tips_detail["author"]

    tips.save()
Esempio n. 12
0
    def post(request, lang):

        sid = transaction.savepoint()

        if lang == 'ja':
            form = TopicForm(request.POST)
            topic_model = Topic()
            video_model = Video()
        else:
            form = TopicEnForm(request.POST)
            topic_model = TopicEn()
            video_model = VideoEn()

        if form.errors:
            messages.add_message(request, messages.INFO,
                                 dict(form.errors.items()))

        if form.is_valid():
            try:
                res_topic = topic_model.create_topic({
                    'new': form.cleaned_data.get('new'),
                    'post_type': form.cleaned_data.get('post_type'),
                    'title': form.cleaned_data.get('title'),
                    'text': form.cleaned_data.get('text'),
                    'thumbnail': form.cleaned_data.get('thumbnail'),
                    'url': form.cleaned_data.get('url'),
                    'event_date': form.cleaned_data.get('event_date'),
                    'button_label': form.cleaned_data.get('button_label'),
                })
                add_videos = form.cleaned_data.get('videos')
                if add_videos:
                    video_model.add_video_from_topic(res_topic.id, add_videos)

                add_images = form.cleaned_data.get('images')
                if add_images:
                    topic_model.add_image(res_topic.id, add_images)

                transaction.savepoint_commit(sid)

                return HttpResponseRedirect('/{}/admin/topics'.format(lang))

            except:
                transaction.savepoint_rollback(sid)
                pass

        select_videos = []
        if form.cleaned_data.get('videos'):
            video_ids = list(map(int, form.cleaned_data.get('videos')))
            select_videos = video_model.get_by_ids(video_ids)

        select_images = []
        if form.cleaned_data.get('images'):
            image_ids = list(map(int, form.cleaned_data.get('images')))
            select_images = Image.get_by_ids(image_ids)

        return TemplateResponse(
            request, 'topic_create.html', {
                'title': '新規投稿 | トピックス | FEED App 管理',
                'select_videos': select_videos,
                'select_images': select_images,
                'form_data': form.cleaned_data,
                'error_messages': get_error_message(request),
                'lang': lang,
                'post_types': [
                    {'name': 'トピック', 'val': 'topic'},
                    {'name': 'イベント', 'val': 'event'},
                ]
            })
Esempio n. 13
0
    def post(request, lang):

        sid = transaction.savepoint()

        if lang == 'ja':
            form = VideoForm(request.POST)
            video_model = Video()
        else:
            form = VideoEnForm(request.POST)
            video_model = VideoEn()
        if form.errors:
            messages.add_message(request, messages.INFO,
                                 dict(form.errors.items()))

        if form.is_valid():
            try:
                res_video = video_model.create_video({
                    'published_at':
                    form.cleaned_data.get('published_at'),
                    'title':
                    form.cleaned_data.get('title'),
                    'text':
                    form.cleaned_data.get('text'),
                    'youtube_id':
                    form.cleaned_data.get('youtube_id'),
                })
                add_introductions = form.cleaned_data.get('introductions')
                if add_introductions:
                    video_model.add_introduction(res_video.id,
                                                 add_introductions)
                add_categories = form.cleaned_data.get('categories')
                if add_categories:
                    video_model.add_category(res_video.id, add_categories)
                add_topics = form.cleaned_data.get('topics')
                if add_topics:
                    video_model.add_topic(res_video.id, add_topics)

                transaction.savepoint_commit(sid)

                return HttpResponseRedirect('/{}/admin/videos'.format(lang))

            except:
                transaction.savepoint_rollback(sid)
                pass

        if lang == 'ja':
            topic_model = Topic()
            introduction_model = Introduction()
        else:
            topic_model = TopicEn()
            introduction_model = IntroductionEn()

        select_categories = []
        if form.cleaned_data.get('categories'):
            category_ids = list(map(int, form.cleaned_data.get('categories')))
            select_categories = Category.get_by_ids(category_ids)

        select_introductions = []
        if form.cleaned_data.get('introductions'):
            title_ids = list(map(int, form.cleaned_data.get('introductions')))
            select_introductions = introduction_model.get_by_ids(title_ids)

        select_topics = []
        if form.cleaned_data.get('topics'):
            topic_ids = list(map(int, form.cleaned_data.get('topics')))
            select_topics = topic_model.get_by_ids(topic_ids)

        select_videos = []
        if form.cleaned_data.get('videos'):
            video_ids = list(map(int, form.cleaned_data.get('videos')))
            select_videos = video_model.get_by_ids(video_ids)

        groups = Group.get_all()

        return TemplateResponse(
            request, 'video_create.html', {
                'title': '新規投稿 | 動画 | FEED App 管理',
                'select_categories': select_categories,
                'select_introductions': select_introductions,
                'select_topics': select_topics,
                'select_videos': select_videos,
                'groups': groups,
                'form_data': form.cleaned_data,
                'error_messages': get_error_message(request),
                'lang': lang,
            })