Esempio n. 1
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. 2
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. 3
0
    def get(_, lang, event_id):
        if lang == 'ja':
            cached_event = Cache.get('api_event_' + str(event_id))
            if cached_event is None:
                event = Topic.get_event_published_by_id(event_id)
                if event is None:
                    return JsonResponse({
                        'message': 'Not Found'
                    }, status=404)

                res = EventSerializer(event).data
                Cache.set('api_event_' + str(event_id), res)
            else:
                res = cached_event

        elif lang == 'en':
            cached_event_en = Cache.get('api_event_en_' + str(event_id))
            if cached_event_en is None:
                event = TopicEn.get_event_published_by_id(event_id)
                if event is None:
                    return JsonResponse({
                        'message': 'Not Found'
                    }, status=404)
                res = EventEnSerializer(event).data
                Cache.set('api_event_en_' + str(event_id), res)
            else:
                res = cached_event_en

        else:
            return JsonResponse({
                'message': 'Not Found'
            }, status=404)

        return JsonResponse(res, safe=False)
Esempio n. 4
0
    def get(_, lang):
        if lang == 'ja':
            cached_topics = Cache.get('api_topics')
            if cached_topics is None:
                res = TopicsSerializer(
                    Topic.get_topic_published_all(), many=True).data
                Cache.set('api_topics', res)
            else:
                res = cached_topics

        elif lang == 'en':
            cached_topics_en = Cache.get('api_topics_en')
            if cached_topics_en is None:
                res = TopicsEnSerializer(
                    TopicEn.get_topic_published_all(), many=True).data
                Cache.set('api_topics_en', res)
            else:
                res = cached_topics_en

        else:
            return JsonResponse({
                'message': 'Not Found'
            }, status=404)

        return JsonResponse(res, safe=False)
Esempio n. 5
0
    def get(_, lang, topic_id):
        if lang == 'ja':
            cached_topic = Cache.get('api_topic_' + str(topic_id))
            if cached_topic is None:
                topic = Topic.get_topic_published_by_id(topic_id)
                if topic is None:
                    return JsonResponse({
                        'message': 'Not Found'
                    }, status=404)

                res = TopicSerializer(topic).data
                Cache.set('api_topic_' + str(topic_id), res)
            else:
                res = cached_topic

        elif lang == 'en':
            cached_topic_en = Cache.get('api_topic_en_' + str(topic_id))
            if cached_topic_en is None:
                topic = TopicEn.get_topic_published_by_id(topic_id)
                if topic is None:
                    return JsonResponse({
                        'message': 'Not Found'
                    }, status=404)
                res = TopicEnSerializer(topic).data
                Cache.set('api_topic_en_' + str(topic_id), res)
            else:
                res = cached_topic_en

        else:
            return JsonResponse({
                'message': 'Not Found'
            }, status=404)

        return JsonResponse(res, safe=False)
Esempio n. 6
0
class VideoForm(forms.Form):
    title = forms.CharField(required=True, error_messages=ERROR_MESSAGES)
    text = forms.CharField(required=True, error_messages=ERROR_MESSAGES)
    youtube_id = forms.CharField(required=True, error_messages=ERROR_MESSAGES)
    published_at = forms.DateTimeField(required=True,
                                       error_messages=ERROR_MESSAGES)
    introductions = forms.MultipleChoiceField(
        required=False,
        widget=forms.CheckboxSelectMultiple,
        choices=lambda: [(v.id, v.id) for v in Introduction.get_all()],
        error_messages=ERROR_MESSAGES)
    topics = forms.MultipleChoiceField(
        required=False,
        widget=forms.CheckboxSelectMultiple,
        choices=lambda: [(v.id, v.id) for v in Topic.get_all()],
        error_messages=ERROR_MESSAGES)
    categories = forms.MultipleChoiceField(
        required=False,
        widget=forms.CheckboxSelectMultiple,
        choices=lambda: [(v.id, v.id) for v in Category.get_all()],
        error_messages=ERROR_MESSAGES)
    videos = forms.MultipleChoiceField(
        required=False,
        widget=forms.CheckboxSelectMultiple,
        choices=lambda: [(v.id, v.id) for v in Video.get_all()],
        error_messages=ERROR_MESSAGES)
Esempio n. 7
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. 8
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. 9
0
    def remove_video_self(cls, video_id):
        all_topic_ids = [v.id for v in Topic.get_all()]
        try:
            video = cls.objects.get(id=video_id)
            for v in all_topic_ids:
                video.video.remove(v)

        except:
            pass
Esempio n. 10
0
    def get(_, lang):
        if lang == 'ja':
            cached_home_events = Cache.get('api_home_events')
            if cached_home_events is None:
                events_res = EventsSerializer(
                    Topic.get_event_home_published_all(), many=True).data
                Cache.set('api_home_events', events_res)
            else:
                events_res = cached_home_events

            cached_home_topics = Cache.get('api_home_topics')
            if cached_home_topics is None:
                topics_res = TopicsSerializer(
                    Topic.get_topic_home_published_all(), many=True).data
                Cache.set('api_home_topics', topics_res)
            else:
                topics_res = cached_home_topics

        elif lang == 'en':
            cached_home_categories_en = Cache.get('api_home_categories_en')
            if cached_home_categories_en is None:
                events_res = EventsEnSerializer(
                    TopicEn.get_event_home_published_all(), many=True).data
                Cache.set('api_categories_en', events_res)
            else:
                events_res = cached_home_categories_en

            cached_home_topics_en = Cache.get('api_home_topics_en')
            if cached_home_topics_en is None:
                topics_res = TopicsEnSerializer(
                    TopicEn.get_topic_home_published_all(), many=True).data
                Cache.set('api_home_topics_en', topics_res)
            else:
                topics_res = cached_home_topics_en

        else:
            return JsonResponse({
                'message': 'Not Found'
            }, status=404)
        
        return JsonResponse({
            'events': events_res,
            'topics': topics_res,
        }, safe=False)
Esempio n. 11
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. 12
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. 13
0
def showtopic(request, gurl_number, turl_number):
    corporation = Corporation.objects(url_number=gurl_number).get()
    topic = Topic.objects(url_number=turl_number).get()
    if request.method == 'POST':
        if "reply" in request.POST:
            reply_form = NewReplyForm(request.POST)
            if reply_form.is_valid():
                content = reply_form.cleaned_data['content']
                reply = Reply(content=content)
                sccard = S_C_Card.objects(user=request.user,
                                          corporation=corporation).get()
                reply.creator = sccard
                reply.creat_time = datetime.datetime.now()
                reply.target = topic
                reply.is_active = True
                reply.save()
                topic.update_author = request.user
                topic.update_time = datetime.datetime.now()
                topic.clicks = topic.clicks - 1
                topic.save()
                return HttpResponseRedirect('/corporation/' +
                                            str(gurl_number) + '/topic/' +
                                            str(turl_number) + '/')

        if "modify" in request.POST:
            modify_form = ModifyTopicForm(request.POST)
            if modify_form.is_valid():
                content = modify_form.cleaned_data['content']
                topic.content = content
                topic.clicks = topic.clicks - 1
                topic.save()
                return HttpResponseRedirect('/corporation/' +
                                            str(gurl_number) + '/topic/' +
                                            str(turl_number) + '/')

    else:
        reply_form = NewReplyForm()
        modify_form = ModifyTopicForm()
        topic.clicks = topic.clicks + 1
        topic.save()
        return render_to_response('corporation/topic_corporation.html', {
            'corporation': corporation,
            'current_user': request.user,
            'reply_form': reply_form,
            'topic': topic,
            'STATIC_URL': STATIC_URL
        },
                                  context_instance=RequestContext(request))
Esempio n. 14
0
    def add_topic(cls, video_id, topic_ids):
        topic_ids = list(map(int, topic_ids))
        all_topic_ids = [v.id for v in Topic.get_all()]
        try:
            video = cls.objects.get(id=video_id)
            for v in all_topic_ids:
                if v in topic_ids:
                    try:
                        video.topic.add(v)
                    except:
                        pass
                else:
                    video.topic.remove(v)

        except:
            pass
Esempio n. 15
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. 16
0
def showtopic(request, gurl_number, turl_number):
    group = Group.objects(url_number=gurl_number).get()
    topic = Topic.objects(url_number=turl_number).get()
    topic.clicks = topic.clicks + 1
    topic.save()
    if request.method == 'POST':
        if "reply" in request.POST:
            reply_form = NewReplyForm(request.POST)
            if reply_form.is_valid():
                content = reply_form.cleaned_data['content']
                reply = Reply(content=content)
                sgcard = S_G_Card.objects(user=request.user, group=group).get()
                reply.creator = sgcard
                reply.creat_time = datetime.datetime.now()
                reply.target = topic
                reply.is_active = True
                reply.save()
                topic.update_author = request.user
                topic.update_time = datetime.datetime.now()
                topic.clicks = topic.clicks - 1
                topic.save()
                return HttpResponseRedirect('/group/' + str(gurl_number) + '/topic/' + str(turl_number) + '/')
            
        if "modify" in request.POST:
            modify_form = ModifyTopicForm(request.POST)
            if modify_form.is_valid():
                content = modify_form.cleaned_data['content']
                topic.content = content
                topic.clicks = topic.clicks - 1
                topic.save()
                return HttpResponseRedirect('/group/' + str(gurl_number) + '/topic/' + str(turl_number) + '/')
        
    else:
        reply_form = NewReplyForm()
        modify_form = ModifyTopicForm()
        topic.clicks = topic.clicks + 1
        topic.save()
        return render_to_response('group/group_topic.html', {'group':group, 'current_user':request.user, 'reply_form':reply_form, 'topic':topic, 'STATIC_URL':STATIC_URL}, context_instance=RequestContext(request))
Esempio n. 17
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. 18
0
def showtopic(request, gurl_number, turl_number):
    corporation = Corporation.objects(url_number=gurl_number).get()
    topic = Topic.objects(url_number=turl_number).get()
    topic.clicks += 1
    topic.save()
    if request.method == 'POST':
        form = NewReplyForm(request.POST)
        if form.is_valid():
            content = form.cleaned_data['content']
            reply = Reply(content=content)
            sccard = S_C_Card.objects(user=request.user, corporation=corporation).get()
            reply.creator = sccard
            reply.creat_time = datetime.datetime.now()
            reply.target = topic
            reply.is_active = True
            reply.save()
            topic.update_author = request.user
            topic.update_time = datetime.datetime.now()
            topic.save()
            return HttpResponseRedirect('/corporation/' + str(gurl_number) + '/topic/' + str(turl_number) + '/')
        
    else:
        form = NewReplyForm()
        return render_to_response('corporation/topic_corporation.html', {'corporation':corporation, 'current_user':request.user, 'form':form, 'topic':topic, 'STATIC_URL':STATIC_URL}, context_instance=RequestContext(request))
Esempio n. 19
0
 def get_topic_creat_top(self):
     from topic.models import Topic
     return Topic.objects(creator=self, is_active=True, is_top=True)
Esempio n. 20
0
 def get_topic_creat_inactive(self):
     from topic.models import Topic
     return Topic.objects(creator=self, is_active=False)
Esempio n. 21
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. 22
0
 def get_topic_corporation_creat_active(self):
     from topic.models import Topic
     return Topic.objects(creator__in=self.get_sccard_all(), is_active=True)
Esempio n. 23
0
 def find_topic(self):
     from topic.models import Topic
     return Topic.objects(creator__in=self.find_group())
Esempio n. 24
0
 def get_topic_corporation_creat_active(self):
     from topic.models import Topic
     return Topic.objects(creator__in=self.get_sccard_all(), is_active=True)
Esempio n. 25
0
 def get_topic_group_creat_active(self):#我创建的小组话题(active)
     from topic.models import Topic
     return Topic.objects(creator__in=self.get_sgcard_all(), is_active=True)
Esempio n. 26
0
def generate_topic_slug(sender, instance: Topic, **kwargs):
    instance.slug = slugify(instance.name)
Esempio n. 27
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. 28
0
 def get_topic_top(self):
     from topic.models import Topic
     return Topic.objects(creator__in=self.get_sccard_all(), is_active=True, is_top=True)
Esempio n. 29
0
 def get_topic_not_locked(self):
     from topic.models import Topic
     return Topic.objects(creator__in=self.get_sccard_all(),
                          is_active=True,
                          is_locked=False)
Esempio n. 30
0
 def get_topic_inactive(self):
     from topic.models import Topic
     return Topic.objects(creator__in=self.get_sccard_all(),
                          is_active=False)
Esempio n. 31
0
 def get_topic_creat_not_locked(self):
     from topic.models import Topic
     return Topic.objects(creator=self, is_active=True, is_locked=False)
Esempio n. 32
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. 33
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. 34
0
 def get_topic_corporation_active(self):#我关注的小组的话题
     from topic.models import Topic
     from relations.models import S_C_Card
     return Topic.objects(creator__in=S_C_Card.objects(corporation__in=self.get_corporation_active()), is_active=True)
Esempio n. 35
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. 36
0
 def find_topic(self):
     from topic.models import Topic
     return Topic.objects(creator__in=self.find_group())
Esempio n. 37
0
 def get_topic_creat_inactive(self):
     from topic.models import Topic
     return Topic.objects(creator=self, is_active=False)
Esempio n. 38
0
 def get_topic_top(self):
     from topic.models import Topic
     return Topic.objects(creator__in=self.get_sccard_all(),
                          is_active=True,
                          is_top=True)
Esempio n. 39
0
 def get_topic_creat_top(self):
     from topic.models import Topic
     return Topic.objects(creator=self, is_active=True, is_top=True)
Esempio n. 40
0
 def get_topic_inactive(self):
     from topic.models import Topic
     return Topic.objects(creator__in=self.get_sccard_all(), is_active=False)
Esempio n. 41
0
 def get_topic_creat_not_locked(self):
     from topic.models import Topic
     return Topic.objects(creator=self, is_active=True, is_locked=False)
Esempio n. 42
0
 def get_topic_not_locked(self):
     from topic.models import Topic
     return Topic.objects(creator__in=self.get_sccard_all(), is_active=True, is_locked=False)
Esempio n. 43
0
    def test_create():
        title = Title.create_title({'title': 'test_title'})

        introduction = Introduction.create_introduction({
            'name':
            'introduction_name',
            'text':
            'text',
            'status':
            1,
            'thumbnail':
            'thumbnail',
            'published_at':
            '2018-09-04 14:57',
        })

        Introduction.add_title(introduction.id, [title.id])

        res1 = Video.create_video({
            'published_at': '2018-09-04 14:57',
            'title': 'video_title1',
            'text': 'video_body1',
            'youtube_id': 'youtube_id',
            'pickup': False,
            'status': 1,
        })

        res = Video.create_video({
            'published_at': '2018-09-04 14:57',
            'title': 'video_title2',
            'text': 'video_body2',
            'youtube_id': 'youtube_id',
            'pickup': False,
            'status': 1,
        })

        Video.add_video_from_video(res.id, [res1.id])
        Video.add_introduction(res.id, [introduction.id])

        video = Video.get_published_by_id(res.id)

        topic = Topic.create_topic({
            'title': 'topic_title',
            'text': 'topic_body',
            'status': 1,
            'images': 'https://aaaa.com/aaa.jpg',
            'url': 'https://yahoo.co.jp',
            'button_label': 'ボタン',
            'published_at': '2018-09-04 14:57'
        })

        pprint(
            IntroductionSerializer(Introduction.get_by_id(
                introduction.id)).data)
        pprint(VideoSerializer(video).data)
        pprint(VideosSerializer(Video.get_all(), many=True).data)
        pprint(TopicSerializer(topic).data)
        pprint(TopicsSerializer(Topic.get_all(), many=True).data)

        Introduction.remove_title(introduction.id)
        Video.remove_video_from_introduction(introduction.id)
        Video.remove_video_self(video.id)

        pprint(
            IntroductionSerializer(Introduction.get_by_id(
                introduction.id)).data)
        pprint(VideoSerializer(Video.get_by_id(video.id)).data)