Exemplo n.º 1
0
def new_topic(request, forum_id):
    form = TopicForm()
    forum = get_object_or_404(Forum, pk=forum_id)

    if request.method == 'POST':
        form = TopicForm(request.POST)

        if form.is_valid():

            topic = Topic()
            topic.title = form.cleaned_data['title']
            topic.description = form.cleaned_data['description']
            topic.forum = forum
            topic.creator = request.user

            topic.save()

            return HttpResponseRedirect(
                reverse('forum:forum-detail', args=(forum_id, )))

    return render(
        request,
        'forum/new-topic.html',
        {
            'form': form,
            'forum': forum,
        },
    )
Exemplo n.º 2
0
    def test_topic_form_valdi(self):
        form = TopicForm(data={
            'text': 'hej',
            'subject': 'cos',
        })

        self.assertTrue(form.is_valid())
Exemplo n.º 3
0
def new_topic(request, slug):
    form = TopicForm()
    forum = get_object_or_404(Forum, slug=slug)

    if request.method == 'POST':
        form = TopicForm(request.POST)

        if form.is_valid():

            topic = Topic()
            topic.title = form.cleaned_data['title']
            topic.description = ''
            topic.creator = request.user
            topic.save()

            topic.forums.add(forum)
            topic.save()

            post = Post()
            post.title = form.cleaned_data['title']
            post.body = form.cleaned_data['description']
            post.creator = request.user
            post.user_ip = request.META['REMOTE_ADDR']
            post.topic = topic
            post.save()
            return HttpResponseRedirect(reverse('topic-detail', args=(slug, topic.id, )))

    return render(request, 'forum/new-topic.html', {'form': form, 'forum': forum})
Exemplo n.º 4
0
def _topic_create_POST(request):
    commit = True
    try:
        post = Post(author=request.forum_user)
        post_form = PostForm(request.POST, instance=post)
        if post_form.is_valid():
            post = post_form.save()
            topic = Topic(author=request.forum_user, first_post=post,
                    last_post=post)
            topic_form = TopicForm(request.POST, instance=topic)
            if topic_form.is_valid():
                topic = topic_form.save()
                post.topic = topic
                post.save()
                for category in topic.categories.all():
                    category.topic_count = category.topic_set.all().count()
                    category.post_count = Post.objects\
                            .filter(topic__in=category.topic_set.all()).count()
                    category.save()
                return redirect(post.get_absolute_url())
        else:
            post_form = PostForm(request.POST)
        ctx = {
            'forum_user': request.forum_user,
            'topic_form': topic_form,
            'post_form': post_form,
        }
        return render(request, 'forum/topic/create.html', ctx)

    finally:
        if commit:
            transaction.commit()
        else:
            transaction.rollback()
Exemplo n.º 5
0
def topic_create(request):
    if request.method == 'POST':
        topicForm = TopicForm(request.POST, prefix="topic")
        messageForm = MessageForm(request.POST, prefix="message")
        if topicForm.is_valid() and messageForm.is_valid():
            topic = topicForm.save(commit=False)
            topic.author = request.user
            topic.creation_date = datetime.datetime.now()
            topic.save()
            message = messageForm.save(commit=False)
            message.author = request.user
            message.creation_date = datetime.datetime.now()
            message.topic = topic
            message.save()

            domain = Site.objects.get_current().domain
            mail_subject = _('A new topic has been posted')
            mail_message = _('%(topic)s : %(topic_url)s') % {'topic': topic.title,
                                                             'topic_url': 'https://%s%s' % (domain, reverse('topic_detail', kwargs={'id': topic.id}))}
            mail_admins(mail_subject, mail_message, fail_silently=(not settings.DEBUG))

            messages.success(request, _('The topic has been saved successfully'))
            return redirect(reverse('topic_detail', kwargs={'id': topic.id}))
        else:
            messages.error(request, _('Data provided are invalid'))
    else:
        topicForm = TopicForm(prefix="topic")
        messageForm = MessageForm(prefix="message")

    return render_to_response('topic/create.html',
                              {'active': 'help',
                               'title': _('New topic'),
                               'topicForm': topicForm,
                               'messageForm': messageForm},
                               context_instance=RequestContext(request))
Exemplo n.º 6
0
def topic_list(request, template='topic/list.html'):
    d = {}
    d['form'] = TopicForm()
    if request.method == 'POST':
        form = TopicForm(request.POST)
        if form.is_valid():
            item = form.save()
            return JsonResponse(data={'id': item.id, 'name': str(item), 'form': TopicForm().as_p(), 'token': get_token(request)})
        else:
            d['form'] = form
            return JsonResponse(data={'form': d['form'].as_p(), 'token': get_token(request)}, success=False)
    d['topic_list'] = Topic.objects.all()
    return render(request, template, d)
Exemplo n.º 7
0
def new_topic(request):
    if request.method != 'POST':
        form = TopicForm()
    else:
        form = TopicForm(request.POST)
        if form.is_valid():
            new_topic = form.save(commit=False)
            new_topic.author = request.user
            new_topic.last_poster = new_topic.author
            new_topic.save()
            return redirect('../')

    return render(request, 'forum/new_topic.html', {'form': form})
Exemplo n.º 8
0
    def add_topic(self, request, *args, **kwargs):
        group = self.get_object()
        check_or_business_error(group in request.user.member_groups.all(),
                                '1010')
        form = TopicForm(data=request.data)
        check_or_business_error(form.is_valid(),
                                '1000',
                                error_data=form.errors)
        topic = form.save(group=group, create_user=request.user, is_topic=True)
        data = TopicDetailSerializer(topic).data

        raise_heat.delay(group.id, 'UserGroup', 2)
        return success_rsp(data)
Exemplo n.º 9
0
def topic_details(request, id, template='topic/details.html'):
    d = {}
    item = get_object_or_404(Topic, pk=id)
    d['form'] = TopicForm(instance=item)
    if request.method == 'POST':
        form = TopicForm(request.POST, instance=item)
        if form.is_valid():
            item = form.save()
            return JsonResponse(data={'form': TopicForm(instance=item).as_p(), 'token': get_token(request)})
        else:
            d['form'] = form
            return JsonResponse(data={'form': d['form'].as_p(), 'token': get_token(request)}, success=False)
    d['topic'] = Topic.objects.get(pk=id)
    return render(request, template, d)
Exemplo n.º 10
0
def new_topic(request, forum_id):
    form = TopicForm()
    forum = get_object_or_404(Forum, pk=forum_id)

    if request.method == 'POST':
        form = TopicForm(request.POST)

        if form.is_valid():

            topic = Topic()
            topic.title = form.cleaned_data['title']
            topic.description = form.cleaned_data['description']
            topic.forum = forum
            topic.creator = request.user
            userToUpdate = UserProfile.objects.get(user=request.user)
            nCredits = userToUpdate.credits
            userToUpdate.credits = int(float(nCredits + 200))

            # TODO: Change status (if points+100>threshold -> status changes)
            # Alert? Maybe return to page with status update info for user.
            # Make Gold/Platinum distinction

            if nCredits + 200 >= GOLD_THRESHOLD:
                newStatus = "Gold"
                userToUpdate.status = newStatus
                userToUpdate.save()
                topic.save()
                return render_to_response(
                    "forum/status_change.html", {'status': newStatus},
                    context_instance=RequestContext(request))
            elif nCredits + 100 >= PLATINUM_THRESHOLD:
                newStatus = "Platinum"
                userToUpdate.status = newStatus
                userToUpdate.save()
                topic.save()
                return render_to_response(
                    "forum/status_change.html", {'status': newStatus},
                    context_instance=RequestContext(request))
            else:
                userToUpdate.save()
                topic.save()
                return HttpResponseRedirect(
                    reverse('forum-detail', args=(forum_id, )))

    return render_to_response('forum/new-topic.html', {
        'form': form,
        'forum': forum,
    },
                              context_instance=RequestContext(request))
Exemplo n.º 11
0
def add_topic(request, section_id):
    context = RequestContext(request)

    if request.method == 'POST':
        form = TopicForm(request.POST)

        if form.is_valid():
            form.save(commit=True)
            return index(request)
        else:
            print(form.errors)
    else:
        form = TopicForm()

    return render_to_response('forum/add_topic.html', {'form': form, 'section_id': section_id}, context)
Exemplo n.º 12
0
def addtopic(request, section_id):

    form = TopicForm(request.POST or None)

    if form.is_valid():
        topic = form.save(commit=False)
        topic.section = get_object_or_404(Section, pk=section_id)
        topic.timestamp = datetime.today()
        topic.author = request.user.username
        topic.save()
        
    return redirect(topics, section_id)
  

        
Exemplo n.º 13
0
def topics(request):
    all_topic_list = Topic.objects.all().order_by('title')
    if request.method == 'POST': 
        user = request.user
        form = TopicForm(request.POST)
        if form.is_valid():
            form.save(user)
        else:
            return render_to_response('forum/topics.html', 
                              {'all_topic_list': all_topic_list, 'form': form},
                              context_instance=RequestContext(request))
    form = TopicForm()
    all_topic_list = Topic.objects.all().order_by('title')
    return render_to_response('forum/topics.html', 
                              {'all_topic_list': all_topic_list, 'form': form},
                              context_instance=RequestContext(request))
Exemplo n.º 14
0
def edit_topic(request, topic_id):
    topic = get_object_or_404(Topic, id=topic_id)
    posts = topic.post_set.order_by('date_added')
    if topic.author != request.user:
        raise Http404

    if request.method != 'POST':
        form = TopicForm(instance=topic)
    else:
        form = TopicForm(request.POST, instance=topic)
        if form.is_valid():
            new_topic = form.save(commit=False)
            new_topic.edit_date = timezone.now()
            new_topic.save()
            return redirect('../')

    return render(request, 'forum/edit_topic.html', {'topic': topic, 'posts': posts, 'form': form})
Exemplo n.º 15
0
def add_topic(request, section_id):
    context = RequestContext(request)

    if request.method == 'POST':
        form = TopicForm(request.POST)

        if form.is_valid():
            form.save(commit=True)
            return index(request)
        else:
            print(form.errors)
    else:
        form = TopicForm()

    return render_to_response('forum/add_topic.html', {
        'form': form,
        'section_id': section_id
    }, context)
Exemplo n.º 16
0
def forum_details(request, id, template="forum/details.html"):
    """View for a forum.
    Autogenerated initially."""
    d = {}
    d["form"] = TopicForm()
    if request.method == "POST":
        form = TopicForm(request.POST)
        if form.is_valid():
            topic = form.save(commit=False)
            topic.forum = Forum.objects.get(pk=id)
            topic.save()
        #             return JsonResponse(data={'id': item.id, 'name': str(item), 'form': TopicForm().as_p(), 'token': get_token(request)})
        else:
            d["form"] = form
    #             return JsonResponse(data={'form': d['form'].as_p(), 'token': get_token(request)}, success=False)
    d["forum"] = Forum.objects.get(pk=id)
    d["topics"] = Topic.objects.filter(forum_id=id)
    return render(request, template, d)
Exemplo n.º 17
0
def topic_create(request):
    if request.method == 'POST':
        topicForm = TopicForm(request.POST, prefix="topic")
        messageForm = MessageForm(request.POST, prefix="message")
        if topicForm.is_valid() and messageForm.is_valid():
            topic = topicForm.save(commit=False)
            topic.author = request.user
            topic.creation_date = datetime.datetime.now()
            topic.save()
            message = messageForm.save(commit=False)
            message.author = request.user
            message.creation_date = datetime.datetime.now()
            message.topic = topic
            message.save()

            domain = Site.objects.get_current().domain
            mail_subject = _('A new topic has been posted')
            mail_message = _('%(topic)s : %(topic_url)s') % {
                'topic':
                topic.title,
                'topic_url':
                'https://%s%s' %
                (domain, reverse('topic_detail', kwargs={'id': topic.id}))
            }
            mail_admins(mail_subject,
                        mail_message,
                        fail_silently=(not settings.DEBUG))

            messages.success(request,
                             _('The topic has been saved successfully'))
            return redirect(reverse('topic_detail', kwargs={'id': topic.id}))
        else:
            messages.error(request, _('Data provided are invalid'))
    else:
        topicForm = TopicForm(prefix="topic")
        messageForm = MessageForm(prefix="message")

    return render_to_response('topic/create.html', {
        'active': 'help',
        'title': _('New topic'),
        'topicForm': topicForm,
        'messageForm': messageForm
    },
                              context_instance=RequestContext(request))
Exemplo n.º 18
0
def new_topic(request, forum_id):
    form = TopicForm()
    forum = get_object_or_404(Forum, pk=forum_id)

    if request.method == 'POST':
        form = TopicForm(request.POST)

        if form.is_valid():

            topic = Topic()
            topic.title = form.cleaned_data['title']
            topic.description = form.cleaned_data['description']
            topic.forum = forum
            topic.creator = request.user
            userToUpdate = UserProfile.objects.get(user=request.user)
            nCredits = userToUpdate.credits
            userToUpdate.credits = int(float(nCredits + 200))

            # TODO: Change status (if points+100>threshold -> status changes)
            # Alert? Maybe return to page with status update info for user.
            # Make Gold/Platinum distinction

            if nCredits + 200 >= GOLD_THRESHOLD:
                newStatus = "Gold"
                userToUpdate.status = newStatus
                userToUpdate.save()
                topic.save()
                return render_to_response("forum/status_change.html", {'status':  newStatus}, context_instance=RequestContext(request))
            elif nCredits + 100 >= PLATINUM_THRESHOLD:
                newStatus = "Platinum"
                userToUpdate.status = newStatus
                userToUpdate.save()
                topic.save()
                return render_to_response("forum/status_change.html", {'status':  newStatus}, context_instance=RequestContext(request))
            else:
                userToUpdate.save()
                topic.save()
                return HttpResponseRedirect(reverse('forum-detail', args=(forum_id, )))

    return render_to_response('forum/new-topic.html', {
        'form': form,
        'forum': forum,
    }, context_instance=RequestContext(request))
Exemplo n.º 19
0
def new_topic(request, forum_id):
    form = TopicForm()
    forum = get_object_or_404(Forum, pk=forum_id)
    user = request.user

    if forum.closed and not user.has_perm('forum.can_post_lock_forum'):
        return render(request, 'personal/basic.html',
                      {'content': ['This forum is locked.']})

    if request.method == 'POST':
        form = TopicForm(request.POST)

        if form.is_valid():

            topic = Topic()
            topic.title = form.cleaned_data['title']
            topic.description = bleach_clean(form.cleaned_data['description'])
            topic.forum = forum
            topic.creator = user

            topic.save()

            tpkPost = Post()
            tpkPost.topic = topic
            tpkPost.title = topic.title
            tpkPost.body = bleach_clean(form.cleaned_data['description'])
            tpkPost.creator = user
            tpkPost.user_ip = get_client_ip(request)

            tpkPost.save()

            return HttpResponseRedirect(
                reverse('topic-detail', args=(
                    topic.id,
                    topic.slug,
                )))

    return render_to_response('forum/new-topic.html', {
        'form': form,
        'forum': forum,
    },
                              context_instance=RequestContext(request))
Exemplo n.º 20
0
def topic_add(request):
    forum_id = request.GET.get('forum')
    forum = get_object_or_404(Forum, pk=forum_id)
    form = TopicForm(request.POST or None)
    if form.is_valid():
	EmailMessage("[BioASQ]: New post in the platform", "There is a new topic in the forum of the BioASQ Participants Area! \nIt is in the category '%s'" %forum, "*****@*****.**", to=["*****@*****.**", "*****@*****.**"]).send()
        topic = Topic.objects.create(
            name=form.cleaned_data['name'],
            forum=forum)
        post = Post.objects.create(
            topic=topic,
            user=request.user,
            content=form.cleaned_data['content'],
        )
        messages.success(request, u'Topic Created Successfully!')
        return redirect(topic)
    context = {'form': form,
               'forum': forum,
            }
    return render(request, 'pybb/topic_add.html', context)
Exemplo n.º 21
0
def new_topic(request, slug):
    form = TopicForm()
    forum = get_object_or_404(Forum, slug=slug)
    
    if request.method == 'POST':
        form = TopicForm(request.POST)

        if form.is_valid():
            topic = Topic()
            topic.title = form.cleaned_data['title']
            topic.description = form.cleaned_data['description']
            topic.forum = forum
            topic.creator = request.user

            topic.save()

            return HttpResponseRedirect(reverse('forum:forum-detail', args=(forum.slug, )))

    context = get_base_context()
    context.update({'form': form, 'forum': forum})
    return render(request, 'forum/new-topic.html', context)
Exemplo n.º 22
0
def new_topic(request, forum_id):
    form = TopicForm()
    forum = get_object_or_404(Forum, pk=forum_id)

    if request.method == 'POST':
        form = TopicForm(request.POST)

        if form.is_valid():

            topic = Topic()
            topic.title = form.cleaned_data['title']
            topic.description = form.cleaned_data['description']
            topic.forum = forum
            topic.creator = request.user

            topic.save()

            return HttpResponseRedirect(reverse('forum-detail', args=(forum_id, )))

    return render_to_response('django_simple_forum/new-topic.html', {
            'form': form,
            'forum': forum,
        }, context_instance=RequestContext(request))
Exemplo n.º 23
0
def new_topic(request, forum_id):
    form = TopicForm()
    forum = get_object_or_404(Forum, pk=forum_id)
    user = request.user
    
    if forum.closed and not user.has_perm('forum.can_post_lock_forum'):
        return render(request, 'personal/basic.html', {'content':['This forum is locked.']})

    if request.method == 'POST':
        form = TopicForm(request.POST)

        if form.is_valid():

            topic = Topic()
            topic.title = form.cleaned_data['title']
            topic.description = bleach_clean(form.cleaned_data['description'])
            topic.forum = forum
            topic.creator = user

            topic.save()

            tpkPost = Post()
            tpkPost.topic = topic
            tpkPost.title = topic.title
            tpkPost.body = bleach_clean(form.cleaned_data['description'])
            tpkPost.creator = user
            tpkPost.user_ip = get_client_ip(request)

            tpkPost.save()

            return HttpResponseRedirect(reverse('topic-detail', args=(topic.id, topic.slug, )))

    return render_to_response('forum/new-topic.html', {
            'form': form,
            'forum': forum,
        }, context_instance=RequestContext(request))
Exemplo n.º 24
0
    def test_topic_form_is_not_valid(self):
        form = TopicForm(data={})

        self.assertFalse(form.is_valid())
        self.assertEqual(len(form.errors), 2)
Exemplo n.º 25
0
def forum_edit_tp(request, bbs_name, tp_id, t_or_p):
    bbs = config.test_bbs_name(bbs_name)
    if not bbs:
        raise Http404
    if t_or_p == 't':
        tp = Topic.objects.select_related('forum', 'author',
                                          'subject').get(id=tp_id)
        forum = tp.forum
        topic_id = tp.id
    else:
        tp = Post.objects.select_related('topic__forum',
                                         'author').get(id=tp_id)
        forum = tp.topic.forum
        topic_id = tp.topic.id
    is_manager = check_manager(request, forum.id)
    is_author = tp.author_id == request.user.id
    # 判断访问权限
    if not (is_manager or is_author):
        error = {'message': u'只有帖子本人、版主、管理员可以编辑'}
        return render_to_response('common/custom_error.html', {
            'config': config,
            'error': error
        })
    # 生成版块层级导航条   1 > 2 > 3 > 4
    forum.path_lists = get_path_lists(forum.path_list, bbs['id'])
    # 获取主题信息
    forum.subjects = forum.subject_set.all().order_by('name')
    if tp.has_attachment:
        tp.attachments = Attachment.objects.filter(tp_id=tp_id)
    attach_form = AttachmentForm()
    if request.method == 'POST':
        if tp.is_topic():
            tp_form = TopicForm(request.POST, instance=tp)
        else:
            tp_form = PostFormFull(request.POST, instance=tp)
        if tp_form.is_valid():
            new_attachments = json.loads(request.POST['new_attachments'])
            del_original_attachments = json.loads(
                request.POST['del_original_attachments'])

            topic_data = tp_form.cleaned_data
            tp.has_attachment = bool(int(request.POST['attachments_num']))
            now = datetime.datetime.now()
            tp.last_edit_time = now
            tp.content = topic_data['content']
            tp.remark = u'本帖最后由 {0} 于 {1} 编辑'.format(
                request.user.nick_name, now.strftime('%Y-%m-%d %H:%M'))
            if tp.is_topic():
                if is_manager:
                    tp.title_color = '#' + request.POST['title_color']
                    tp.title_bold = topic_data['title_bold']
                else:
                    tp.title_color = tp.title_color
                    tp.title_bold = tp.title_bold
                tp.subject_id = request.POST['subject']
                tp.read_level = topic_data['read_level']
                tp.title = topic_data['title']
                tp.is_hide = topic_data['is_hide']
                tp.save(force_update=True,
                        update_fields=[
                            'last_edit_time', 'content', 'subject',
                            'read_level', 'title', 'is_hide', 'title_color',
                            'title_bold', 'has_attachment', 'remark'
                        ])
            else:
                tp.save(force_update=True,
                        update_fields=[
                            'last_edit_time', 'content', 'has_attachment',
                            'remark'
                        ])

            if new_attachments:
                # 添加新加的附件到数据库
                attachs = []
                for attach in new_attachments:
                    file_name = attach['file_name']
                    file_type = attach['type']
                    file_size = attach['size']
                    file_path = attach['file_path']
                    attach_download_level = attach['download_level']
                    attachs.append(
                        Attachment(user=request.user,
                                   tp_id=tp.id,
                                   file=file_path,
                                   file_name=file_name,
                                   file_type=file_type,
                                   file_size=file_size,
                                   download_level=attach_download_level))
                Attachment.objects.bulk_create(attachs)
            if del_original_attachments:
                # 删除已经存在附件
                del_id_list = [
                    attach['storage_name']
                    for attach in del_original_attachments
                ]
                Attachment.objects.filter(id__in=del_id_list).delete()
            return HttpResponseRedirect(
                reverse('topic', args=(bbs['name'], topic_id)))
    else:
        if tp.is_topic():
            tp_form = TopicForm(instance=tp)
        else:
            tp_form = PostFormFull(instance=tp)

    return render_to_response(bbs_name + '/forum/edit_topic.html', {
        'config': config,
        'tp_form': tp_form,
        'forum': forum,
        'tp': tp,
        'is_manager': is_manager,
        'is_author': is_author,
        'bbs': bbs,
        'attach_form': attach_form
    },
                              context_instance=RequestContext(request))
Exemplo n.º 26
0
def forum_new_topic(request, bbs_name, forum_tag):
    bbs = config.test_bbs_name(bbs_name)
    if not bbs:
        raise Http404
    forum = get_object_or_404(Forum, tag=forum_tag, belong=bbs['id'])
    is_manager = check_manager(request, forum.id)
    # 判断访问权限
    result = check_visit_level(request, forum.visit_level)
    if result:
        return result
    # 生成版块层级导航条   1 > 2 > 3 > 4
    forum.path_lists = get_path_lists(forum.path_list, bbs['id'])
    # 获取主题信息
    forum.subjects = get_or_create_subjects(forum)
    attach_form = AttachmentForm()
    if request.method == 'GET':
        topic_form = TopicForm()
        poll_form = PollForm()
    else:
        user = request.user
        topic_form = TopicForm(request.POST)
        poll_form = PollForm(request.POST)
        if topic_form.is_valid():
            topic_data = topic_form.cleaned_data
            now = datetime.datetime.now()
            subject_id = request.POST['subject']
            read_level = topic_data['read_level']
            author = user
            title = topic_data['title']
            content = topic_data['content']
            if is_manager:
                title_color = '#' + request.POST['title_color']
                title_bold = topic_data['title_bold']
            else:
                title_color = "#000000"
                title_bold = False
            post_time = now
            is_hide = topic_data['is_hide']
            is_poll = topic_data['is_poll']
            has_img = '<img' in content
            ip = get_remote_ip(request)
            attachments = json.loads(request.POST['attachments'])
            # 在此添加topic到数据库
            topic = Topic.objects.create(forum=forum,
                                         subject_id=subject_id,
                                         read_level=read_level,
                                         author=author,
                                         title=title,
                                         content=content,
                                         title_bold=title_bold,
                                         title_color=title_color,
                                         post_time=post_time,
                                         last_edit_time=post_time,
                                         is_hide=is_hide,
                                         is_poll=is_poll,
                                         ip=ip,
                                         has_attachment=bool(attachments),
                                         has_img=has_img)
            if is_poll:
                if poll_form.is_valid():
                    poll_data = poll_form.cleaned_data
                    # 如果是投票贴,获取投票各项参数,若未设置过期时间,默认为7天
                    poll_descr = poll_data['descr']
                    is_multi = poll_data['is_multi']
                    is_poll_visible = poll_data['is_visible']
                    expiry = poll_data['expiry']
                    max_choices = poll_data['max_choices']
                    poll_options_str = request.POST['poll_options']
                    # 前台使用jquery保证只要勾选了is_poll,就必须填写至少两项options
                    poll_options = json.loads(poll_options_str)  # 包含投票选项字符串的集合
                    # 有poll 在此添加topic到数据库
                    poll = Poll.objects.create(topic=topic,
                                               descr=poll_descr,
                                               is_multi=is_multi,
                                               is_visible=is_poll_visible,
                                               max_choices=max_choices,
                                               expiry=expiry)
                    options = []
                    i = 1
                    for option in poll_options:
                        options.append(
                            PollOption(poll=poll,
                                       option=option,
                                       display_order=i))
                        i += 1
                    PollOption.objects.bulk_create(options)
                else:
                    # rollback 事务
                    return render_to_response(
                        bbs_name + '/forum/new_topic.html', {
                            'bbs': bbs,
                            'forum': forum,
                            'config': config,
                            'topic_form': topic_form,
                            'is_manager': is_manager,
                            'attach_form': attach_form,
                            'poll_form': poll_form
                        },
                        context_instance=RequestContext(request))
            # topic创建成功后,如果有附件,创建附件
            if attachments:
                # 上传附件不为空,获取附件信息
                attachs = []
                for attach in attachments:
                    file_name = attach['file_name']
                    file_type = attach['type']
                    file_size = attach['size']
                    file_path = attach['file_path']
                    attach_download_level = attach['download_level']
                    attachs.append(
                        Attachment(user=author,
                                   tp_id=topic.id,
                                   file=file_path,
                                   file_name=file_name,
                                   file_type=file_type,
                                   file_size=file_size,
                                   download_level=attach_download_level))
                Attachment.objects.bulk_create(attachs)
            # 所属论坛信息更新,根据最后一次发帖/回帖时间是不是今天选择不同sql命令

            update_after_topic_post(request.user, forum, post_time, topic,
                                    True)

            return HttpResponseRedirect(
                reverse('topic', args=(bbs['name'], topic.id)))
    return render_to_response(bbs_name + '/forum/new_topic.html', {
        'bbs': bbs,
        'forum': forum,
        'config': config,
        'topic_form': topic_form,
        'is_manager': is_manager,
        'attach_form': attach_form,
        'poll_form': poll_form
    },
                              context_instance=RequestContext(request))
Exemplo n.º 27
0
def new_topic(request, forum_id):
    if 'userid' in request.session:
        form = TopicForm()
        forum = get_object_or_404(Forum, pk=forum_id)

        status = 'student'
        stud_obj = student.objects.get(pk=request.session['userid'])
        username = stud_obj.uname

        if request.method == 'POST':
            form = TopicForm(request.POST)

            if form.is_valid():
                topic = Topic()
                topic.title = form.cleaned_data['title']
                topic.description = form.cleaned_data['description']
                topic.forum = forum
                obj = student.objects.get(pk=request.session['userid'])
                topic.creator = obj

                topic.save()

                return HttpResponseRedirect(
                    reverse('forum-detail', args=(forum_id, )))

        return render(
            request,
            'forum/new-topic.html',
            {
                'form': form,
                'forum': forum,
                'username': username,
                'status': status
            },
        )
    elif 'instructorid' in request.session:
        form = TopicForm()
        forum = get_object_or_404(Forum, pk=forum_id)

        status = 'instructor'
        inst_obj = instructor.objects.get(pk=request.session['instructorid'])
        username = inst_obj.uname

        if request.method == 'POST':
            form = TopicForm(request.POST)

            if form.is_valid():
                topic = Topic()
                topic.title = form.cleaned_data['title']
                topic.description = form.cleaned_data['description']
                topic.forum = forum
                obj = instructor.objects.get(
                    pk=request.session['instructorid'])
                topic.by_instructor = obj

                topic.save()

                return HttpResponseRedirect(
                    reverse('forum-detail', args=(forum_id, )))

        return render(
            request,
            'forum/new-topic.html',
            {
                'form': form,
                'forum': forum,
                'username': username,
                'status': status
            },
        )
    else:
        return HttpResponseRedirect('/joinus/login/')