示例#1
0
 def test_save(self):
     self.assertEqual(self.poll_1.choice_set.get(pk=1).votes, 1)
     self.assertEqual(self.poll_1.choice_set.get(pk=2).votes, 0)
     
     # Test the first choice.
     form_1 = PollForm({'choice': 1}, instance=self.poll_1)
     form_1.save()
     self.assertEqual(self.poll_1.choice_set.get(pk=1).votes, 2)
     self.assertEqual(self.poll_1.choice_set.get(pk=2).votes, 0)
     
     # Test the second choice.
     form_2 = PollForm({'choice': 2}, instance=self.poll_1)
     form_2.save()
     self.assertEqual(self.poll_1.choice_set.get(pk=1).votes, 2)
     self.assertEqual(self.poll_1.choice_set.get(pk=2).votes, 1)
     
     # Test the other poll.
     self.assertEqual(self.poll_2.choice_set.get(pk=3).votes, 1)
     self.assertEqual(self.poll_2.choice_set.get(pk=4).votes, 0)
     self.assertEqual(self.poll_2.choice_set.get(pk=5).votes, 0)
     
     form_3 = PollForm({'choice': 5}, instance=self.poll_2)
     form_3.save()
     self.assertEqual(self.poll_2.choice_set.get(pk=3).votes, 1)
     self.assertEqual(self.poll_2.choice_set.get(pk=4).votes, 0)
     self.assertEqual(self.poll_2.choice_set.get(pk=5).votes, 1)
示例#2
0
def user_polls_edit_view(request, question_id):
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        current_question = Question.objects.get(id=question_id)
        form = PollForm(request.POST, instance=current_question)
        current_choices = Choice.objects.filter(question=current_question)
        formset = ChoiceFormset(request.POST, instance=current_question)
        # check whether it's valid:
        if form.is_valid() and formset.is_valid:
            question = form.save(commit=False)
            question.save()
            for form in formset:
                # so that `book` instance can be attached.
                choice = form.save(commit=False)
                choice.save()
            return render(request, 'polls/detail.html', {
                'question': question})

        # if a GET (or any other method) we'll create a blank form

    try:
        my_record = Question.objects.get(id=question_id)
        form = PollForm(instance=my_record)
        formset = ChoiceFormset(instance=my_record)
    except KeyError:
        HttpResponse("Something went wrong!")

    return render(request, 'polls/user/editpoll.html',
                  {'formPoll': form, 'formset': formset,
                   'question': my_record,
                   })
示例#3
0
def create(request):
    """
    Create a new, empty poll.
    """
    if request.method == 'POST':
        poll_form = PollForm(request.POST)
        if poll_form.is_valid():

            np = poll_form.save(commit=False)

            p = np  # höhö

            if not np.url:
                np.url = p.url_from_name(np.name)

            np.save()

            assign_perm('change_poll', request.user, np)
            assign_perm('delete_poll', request.user, np)

            return redirect('poll-edit-questions', np.url)

    else:
        poll_form = PollForm()

    return render(request, 'polls/poll/create.html', {'poll_form': poll_form})
示例#4
0
def user_polls_create_view(request):
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = PollForm(request.POST)
        formset = ChoiceFormset(request.POST)
        # check whether it's valid:
        if form.is_valid() and formset.is_valid():
            question = form.save()
            question.user = request.user
            question.save()
            for form in formset:
                # so that `book` instance can be attached.
                choice = form.save(commit=False)
                choice.question = question
                choice.save()
            return render(request, 'polls/detail.html', {
                'question': question})

        # if a GET (or any other method) we'll create a blank form
    else:
        form = PollForm()

    return render(request, 'polls/user/createpoll.html',
                  {'formPoll': form, 'formset': ChoiceFormset(queryset=Choice.objects.none()),
                   })
示例#5
0
def new_thread(request, subject_id):
    """
    Add a new thread
    """
    subject = get_object_or_404(Subject, pk=subject_id)
    poll_subject_formset_class = formset_factory(PollSubjectForm, extra=3)

    # If request is POST, create a new thread
    if request.method == "POST":
        thread_form = ThreadForm(request.POST)
        post_form = PostForm(request.POST)
        poll_form = PollForm(request.POST)
        poll_subject_formset = poll_subject_formset_class(request.POST)

        # Save Thread and Post
        if thread_form.is_valid() and post_form.is_valid():
            thread = thread_form.save(False)
            thread.subject = subject
            thread.user = request.user
            thread.save()

            post = post_form.save(False)
            post.user = request.user
            post.thread = thread
            post.save()

            # If user creates a Poll then save it too
            if poll_form.is_valid() and poll_subject_formset.is_valid():
                poll = poll_form.save(False)
                poll.thread = thread
                poll.save()

                for subject_form in poll_subject_formset:
                    subject = subject_form.save(False)
                    subject.poll = poll
                    subject.save()

            messages.success(request, "You have created a new thread!")

            return redirect(reverse('thread', args=[thread.pk]))

    # If request is GET, render blank form
    else:
        thread_form = ThreadForm()
        post_form = PostForm()
        poll_form = PollForm()
        poll_subject_formset = poll_subject_formset_class()

    args = {
        'thread_form': thread_form,
        'post_form': post_form,
        'subject': subject,
        'poll_form': poll_form,
        'poll_subject_formset': poll_subject_formset,
    }

    args.update(csrf(request))

    return render(request, 'forum/thread_form.html', args)
示例#6
0
def new_thread(request, subject_id):

    subject = get_object_or_404(Subject, pk=subject_id)
    poll_subject_formset_class = formset_factory(PollSubjectForm, extra=3)

    if request.method == "POST":
        thread_form = ThreadForm(request.POST)
        post_form = PostForm(request.POST)
        poll_form = PollForm(request.POST)
        poll_subject_formset = poll_subject_formset_class(request.POST)
        if (thread_form.is_valid() and
                post_form.is_valid() and
                poll_form.is_valid() and
                poll_subject_formset.is_valid()):

            thread = thread_form.save(False)
            thread.subject = subject
            thread.user = request.user
            thread.save()

            post = post_form.save(False)
            post.user = request.user
            post.thread = thread
            post.save()

            if 'is_a_poll' in request.POST:
                poll = poll_form.save(False)
                poll.thread = thread
                poll.save()

                for subject_form in poll_subject_formset:
                    subject = subject_form.save(False)
                    subject.poll = poll
                    subject.save()

                messages.success(request, "You have created a new poll!")
            else:
                messages.success(request, "You have create a new thread!")

            return redirect(reverse('thread', args={thread.pk}))
    else:
        thread_form = ThreadForm()
        post_form = PostForm()
        poll_form = PollForm()
        poll_subject_formset = poll_subject_formset_class()

    args = {
        'thread_form': thread_form,
        'post_form': post_form,
        'subject': subject,
        'poll_form': poll_form,
        'poll_subject_formset': poll_subject_formset,
    }
    args.update(csrf(request))

    return render(request, 'forum/thread_form.html', args)
def new_thread(request, subject_id):
    """Submitting a new thread"""
    subject = get_object_or_404(Subject, pk=subject_id)
    poll_subject_formset = formset_factory(PollSubjectForm, extra=3)
    if request.method == 'POST':
        thread_form = ThreadForm(request.POST)
        post_form = PostForm(request.POST)
        poll_form = PollForm(request.POST)
        poll_subject_formset = poll_subject_formset(request.POST)
        # Checking if a poll is being submitted
        if request.POST.get('is_a_poll'):
            if thread_form.is_valid() and post_form.is_valid(
            ) and poll_form.is_valid() and poll_subject_formset.is_valid():
                this_thread = thread_form.save(False)
                this_thread.subject = subject
                this_thread.user = request.user
                this_thread.save()
                post = post_form.save(False)
                post.user = request.user
                post.thread = this_thread
                post.save()
                poll = poll_form.save(False)
                poll.thread = this_thread
                poll.save()
                for subject_form in poll_subject_formset:
                    subject = subject_form.save(False)
                    subject.poll = poll
                    subject.save()
                messages.success(request, 'You have created a new thread')
                return redirect(reverse('thread', args={this_thread.pk}))
        else:
            if thread_form.is_valid() and post_form.is_valid():
                this_thread = thread_form.save(False)
                this_thread.subject = subject
                this_thread.user = request.user
                this_thread.save()
                post = post_form.save(False)
                post.user = request.user
                post.thread = this_thread
                post.save()
                messages.success(request, 'You have created a new thread')
                return redirect(reverse('thread', args={this_thread.pk}))
    else:
        thread_form = ThreadForm()
        post_form = PostForm()
        poll_form = PollForm()
        poll_subject_formset = poll_subject_formset()
    args = {
        'thread_form': thread_form,
        'post_form': post_form,
        'subject': subject,
        'poll_form': poll_form,
        'poll_subject_formset': poll_subject_formset,
    }
    args.update(csrf(request))
    return render(request, 'forum/thread_form.html', args)
示例#8
0
def new_thread(request, subject_id):
    subject = get_object_or_404(Subject, pk=subject_id)
    poll_subject_formset_class = formset_factory(PollSubjectForm, extra=3)

    if request.method == "POST":
        thread_form = ThreadForm(request.POST)
        post_form = PostForm(request.POST)
        poll_form = PollForm(request.POST)
        poll_subject_formset = poll_subject_formset_class(request.POST)

        # from code-institute solution as I couldn't figure out another way
        # create three variables, the first one stores the results of checking if 'is_a_poll' is in the POST method.
        is_a_poll = request.POST.get('is_a_poll')
        # The second stores the results from checking if thread_form and post_form is valid
        thread_valid = thread_form.is_valid() and post_form.is_valid()
        # The third stores the results from checking if poll_form and poll_subject_formset is valid
        poll_valid = poll_form.is_valid() and poll_subject_formset.is_valid()

        # create if statements to use the above variables.
        # create just a thread
        if (thread_valid and not is_a_poll):
            thread = save_thread(thread_form, post_form, subject, request.user)
            messages.success(request, "You have created a new thread!")
            return redirect(reverse('thread', args=[thread.pk]))

        # Create a thread with a poll
        if (thread_valid and is_a_poll and poll_valid):
            thread = save_thread(thread_form, post_form, subject, request.user)
            save_poll(poll_form, poll_subject_formset, thread)
            messages.success(request,
                             "You have created a new thread with a poll!")
            return redirect(reverse('thread', args=[thread.pk]))

    else:
        thread_form = ThreadForm()
        post_form = PostForm()
        poll_form = PollForm()
        poll_subject_formset = poll_subject_formset_class()

    args = {
        'thread_form': thread_form,
        'post_form': post_form,
        'subject': subject,
        'poll_form': poll_form,
        'poll_subject_formset': poll_subject_formset,
    }

    args.update(csrf(request))

    return render(request, 'forum/thread_form.html', args)
示例#9
0
def poll_create(request):
    if request.method == 'POST':
        form = PollForm(request.POST, request.FILES)
        if form.is_valid():
            newpoll = Poll(subject=request.POST['subject'],
                           picture=request.FILES['picture'], detail=request.POST['detail'], password=request.POST['password'],
                           create_by=User.objects.get(pk=request.user.id), start_date=request.POST['start_date'],
                           end_date=request.POST['end_date'], create_date=datetime.datetime.now())
            newpoll.save()
            return redirect('index')
    else:
        form = PollForm()
    # if request.user.is_authenticated:
    return render(request, 'polls/create.html', {'form': form})
示例#10
0
def detail(request, poll_id):
    p = get_object_or_404(Poll.published.all(), pk=poll_id)
    
    if request.method == 'POST':
        form = PollForm(request.POST, instance=p)
        
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('polls_results', kwargs={'poll_id': p.id}))
    else:
        form = PollForm(instance=p)
    
    return render_to_response('polls/detail.html', {
        'poll': p,
        'form': form,
    }, context_instance=RequestContext(request))
示例#11
0
文件: views.py 项目: tapiau/CivilHub
 def post(self, request, *args, **kwargs):
     form = self.form_class(request.POST)
     if form.is_valid():
         obj = form.save(commit=False)
         obj.creator = self.request.user
         obj.image = request.FILES.get('image')
         obj.save()
         # Without this next line the tags won't be saved.
         form.save_m2m()
         for f in request.FILES:
             print f
         for key, val in request.POST.iteritems():
             if 'answer_txt_' in key:
                 a = Answer(poll=obj, answer=val)
                 a.save()
         return redirect(obj.get_absolute_url())
     else:
         context = {
             'title': _('Create new poll'),
             'location': form.cleaned_data['location'],
             'links': links['polls'],
             'appname': 'poll-create',
             'form': PollForm(request.POST),
         }
         return render(request, self.template_name, context)
示例#12
0
def main(request):
    title = 'Polls'
    polls = Poll.filtered.open_for_user(request.user)

    for poll in polls:
        poll.form = PollForm(poll=poll, user=request.user)

    return TemplateResponse(request, 'polls/main.html', locals())
示例#13
0
 def test_init(self):
     # Test successful init without data.
     form = PollForm(instance=self.poll_1)
     self.assertTrue(isinstance(form.instance, Poll))
     self.assertEqual(form.instance.pk, self.poll_1.pk)
     self.assertEqual([c for c in form.fields['choice'].choices], [(1, u'Yes'), (2, u'No')])
     
     # Test successful init with data.
     form = PollForm({'choice': 3}, instance=self.poll_2)
     self.assertTrue(isinstance(form.instance, Poll))
     self.assertEqual(form.instance.pk, self.poll_2.pk)
     self.assertEqual([c for c in form.fields['choice'].choices], [(3, u'Alright.'), (4, u'Meh.'), (5, u'Not so good.')])
     
     # Test a failed init without data.
     self.assertRaises(KeyError, PollForm)
     
     # Test a failed init with data.
     self.assertRaises(KeyError, PollForm, {})
示例#14
0
def new(request):
    """
    Create a new Poll, with 1 initial "Pitch" for
    a given choice. The "Pitch" is a short blurb
    on why you should choice a given choice.

    The Pitch that the User fills out determines
    that User's choice for this particular Poll.

    TODO: Write Unit tests
    """
    if request.method == 'POST':
        poll_form = PollForm(request.POST)
        pitch_form = PitchForm(request.POST)
        if poll_form.is_valid() and pitch_form.is_valid():
            poll_inst = poll_form.save(commit=False)
            question = poll_form.cleaned_data["question"]
            if question in DISALLOWED_QUESTIONS:
                poll_form.errors.extra = "Invalid Question, please try a different one."
            if not hasattr(poll_form.errors, "extra"):
                poll_inst.owner = request.user
                poll_inst.last_modified = datetime.now()
                poll_inst.guid = create_poll_guid(question)
                try:
                    poll_inst.save()
                    #TODO add a function to Pitch to make this cleaner:
                    pitch_inst = pitch_form.save(commit=False)
                    pitch_inst.poll = poll_inst
                    pitch_inst.choice_id = "a"
                    pitch_inst.editor = poll_inst.owner
                    pitch_inst.save()
                    pitch_inst.vote()
                    return HttpResponseRedirect('/')  # Redirect after POST
                except IntegrityError:
                    poll_form.errors.extra = "Your Question already exists, possibly created by another User."
    else:
        poll_form = PollForm()
        pitch_form = PitchForm()
    args = {
        "poll_form": poll_form,
        "pitch_form": pitch_form,
        "user": request.user
    }
    return render_to_response("polls/new.html", args)
示例#15
0
def new_thread(request, subject_id):
    subject = get_object_or_404(Subject, pk=subject_id)
    poll_subject_formset_class = formset_factory(PollSubjectForm, extra=3)

    if request.method == "POST":
        thread_form = ThreadForm(request.POST)
        post_form = PostForm(request.POST)
        poll_form = PollForm(request.POST)
        poll_subject_formset = poll_subject_formset_class(request.POST)

        is_a_poll = request.POST.get('is_a_poll')
        thread_valid = thread_form.is_valid() and post_form.is_valid()
        poll_valid = poll_form.is_valid() and poll_subject_formset.is_valid()

        if (thread_valid and not is_a_poll):
            thread = save_thread(thread_form, post_form, subject, request.user)
            messages.success(request, "You have created a new thread!")
            return redirect(reverse('thread', args=[thread.pk]))


        if (thread_valid and is_a_poll and poll_valid):
            thread = save_thread(thread_form, post_form, subject, request.user)
            save_poll(poll_form, poll_subject_formset, thread)
            messages.success(
                request, "You have created a new thread with a poll!")
            return redirect(reverse('thread', args=[thread.pk]))

    else:
        thread_form = ThreadForm()
        post_form = PostForm()
        poll_form = PollForm()
        poll_subject_formset = poll_subject_formset_class()

    args = {
        'thread_form': thread_form,
        'post_form': post_form,
        'subject': subject,
        'poll_form': poll_form,
        'poll_subject_formset': poll_subject_formset
    }

    args.update(csrf(request))

    return render(request, 'forum/thread_form.html', args)
示例#16
0
def vote(request):
    poll = get_object_or_404(Poll, id=request.POST.get('poll_id', None))
    form = PollForm(request.POST, user=request.user, poll=poll)

    if form.is_valid():
        form.save()

        return redirect('polls:thanks')

    raise Http404
示例#17
0
def add_poll(request):
    form = PollForm()
    if request.method == 'POST':
        form = PollForm(request.POST)
        if form.is_valid():
            new_form = form.save(commit=False)
            new_form.pub_date = datetime.datetime.now()
            new_form.owner = request.user
            new_form.save()
            choice1 = Choice(poll=new_form,
                             choice_text=form.cleaned_data['choice1']).save()
            choice2 = Choice(poll=new_form,
                             choice_text=form.cleaned_data['choice2']).save()
            messages.success(
                request,
                "Poll and Choices Added!!",
                extra_tags="alert alert-warning alert-dismissible fade show")
            return redirect('polls:list')

    return render(request, 'polls/add_polls.html', {'form': form})
示例#18
0
文件: views.py 项目: tapiau/CivilHub
 def get(self, request, *args, **kwargs):
     slug = kwargs['slug']
     location = Location.objects.get(slug=slug)
     ctx = {
         'title': _('Create new poll'),
         'location': location,
         'links': links['polls'],
         'appname': 'poll-create',
         'form': PollForm(initial={'location': location})
     }
     return render(request, self.template_name, ctx)
    def post(self, request, poll_id):
        poll = get_object_or_404(Poll.objects.all(), pk=poll_id)
        form = PollForm(request.POST, instance=poll)

        if form.is_valid():
            form.save()
        else:
            return Response(content=form.errors, status=400)

        return Response(
            status=303,
            headers={'Location': reverse('polls_api_results', args=[poll_id])})
示例#20
0
    def get(self, request, *args, **kwargs):
        context = super(PollVoteView, self).get_context_data(**kwargs)

        # get a Poll instance from the db and add it to the context
        poll_id = kwargs.get('poll_id')
        poll = get_object_or_404(Poll, pk=poll_id)
        context['poll'] = poll

        # add poll form to the context
        questions = [field.title for field in poll.template.fields]
        context['form'] = PollForm(questions=questions)

        return self.render_to_response(context)
示例#21
0
def new_thread_get(request, subject, poll_subject_formset):
    thread_form = ThreadForm()
    post_form = PostForm(request.POST)
    poll_form = PollForm()
    poll_subject_formset = poll_subject_formset()

    args = {
        'thread_form': thread_form,
        'post_form': post_form,
        'subject': subject,
        'poll_form': poll_form,
        'poll_subject_formset': poll_subject_formset
    }

    args.update(csrf(request))

    return render(request, 'forum/thread_form.html', args)
示例#22
0
def neighborhood_home(request):
    if request.method == 'POST':
        report_form = ReportForm(request.POST)
        if report_form.is_valid():
            report = report_form.save()
            report.sender = request.user
            report.time = timezone.now()
            report.save()
    report_form = ReportForm()
    announcement_form = AnnouncementForm()
    pollform = PollForm()
    neighborhood = request.user.userprofile.house.neighborhood
    request.session['neighborhood_id'] = neighborhood.id
    feed = Feed.objects.get(neighborhood=neighborhood)
    feedposts = get_recent_posts(feed.id)
    eventform = EventForm()
    request.session['feed_id'] = feed.id
    user_prof = request.user.userprofile
    # return the 20 most recent activities from the user
    activities = Activity.objects.filter(
        user=request.user).order_by('date')[:20]
    # return the 20 most recent user messages
    messages = Message.objects.filter(
        receiver=request.user).order_by('time')[:20]
    board_permissions = user_prof.is_board_member()
    polls = Poll.objects.filter(
        neighborhood=neighborhood,
        pub_date__lte=timezone.now()).order_by('-pub_date')

    markers = Marker.objects.all().filter(neighborhood_id=neighborhood.id)
    return render(
        request, 'neighborhood/map_home.html', {
            'neighborhood': neighborhood,
            'user': user_prof,
            'activities': activities,
            'messages': messages,
            'markers': markers,
            'feedposts': feedposts,
            'report_form': report_form,
            'announcement_form': announcement_form,
            'pollform': pollform,
            'eventform': eventform,
            'board_permissions': board_permissions,
            'polls': polls
        })
示例#23
0
def new_thread_post(request, subject, poll_subject_formset):
    thread_form = ThreadForm(request.POST)
    post_form = PostForm(request.POST)
    poll_form = PollForm(request.POST)
    poll_subject_formset = poll_subject_formset(request.POST)

    all_forms = [thread_form, post_form, poll_form, poll_subject_formset]
    all_forms_valid = all(f.is_valid() for f in all_forms)
    if all_forms_valid:

        thread = thread_form.save(False)
        thread.subject = subject
        thread.user = request.user
        thread.save()

        post = post_form.save(False)
        post.user = request.user
        post.thread = thread
        post.save()

        poll = poll_form.save(False)
        poll.thread = thread
        poll.save()

        for subject_form in poll_subject_formset:
            subject = subject_form.save(False)
            subject.poll = poll
            subject.save()

        messages.success(request, "You have created a new thread!")

        return redirect(reverse('thread', args={thread.pk}))

    else:
        args = {
            'thread_form': thread_form,
            'post_form': post_form,
            'subject': subject,
            'poll_form': poll_form,
            'poll_subject_formset': poll_subject_formset
        }

        args.update(csrf(request))

        return render(request, 'forum/thread_form.html', args)
示例#24
0
def new_thread(request, subject_id):
    """
    Create new thread with accompanying post
    """
    subject = get_object_or_404(Subject, pk=subject_id)

    poll_subject_formset = formset_factory(PollSubjectForm, extra=3)

    if request.method == "POST":
        thread_form = ThreadForm(request.POST)
        post_form = PostForm(request.POST)
        poll_form = PollForm(request.POST)
        poll_subject_formset = poll_subject_formset(request.POST)

        if request.POST.get('is_a_poll', None):

            # save the thread with a poll
            if thread_form.is_valid() and post_form.is_valid()\
                    and poll_form.is_valid() \
                    and poll_subject_formset.is_valid():
                thread = thread_form.save(False)
                thread.subject = subject
                thread.user = request.user
                thread.save()

                post = post_form.save(False)
                post.user = request.user
                post.thread = thread
                post.save()

                poll = poll_form.save(False)
                poll.thread = thread
                poll.save()

                for subject_form in poll_subject_formset:
                    subject = subject_form.save(False)
                    subject.poll = poll
                    subject.save()

                messages.success(request, "You have created a new thread!")

                return redirect(reverse('thread', args={thread.pk}))

        else:
            # save the thread without a poll
            if thread_form.is_valid() and post_form.is_valid(
            ) and poll_subject_formset.is_valid():
                thread = thread_form.save(False)
                thread.subject = subject
                thread.user = request.user
                thread.save()

                post = post_form.save(False)
                post.user = request.user
                post.thread = thread
                post.save()

                messages.success(request, "You have created a new thread!")

                return redirect(reverse('thread', args={thread.pk}))

    else:
        thread_form = ThreadForm()
        post_form = PostForm(request.POST)
        poll_form = PollForm()
        poll_subject_formset = poll_subject_formset()

    args = {
        'thread_form': thread_form,
        'post_form': post_form,
        'subject': subject,
        'poll_form': poll_form,
        'poll_subject_formset': poll_subject_formset
    }

    args.update(csrf(request))

    return render(request, 'forum/thread_form.html', args)
示例#25
0
 def test_poll_form_question_field_label(self):
     form = PollForm()
     self.assertTrue(
         form.fields['question_text'].label == None
         or form.fields['question_text'].label == 'Question text')
示例#26
0
 def get_form(self):
     """Get the form to create or update a poll."""
     return PollForm(type=PollType.MANUAL.name)
示例#27
0
def new_thread(request, subject_id):
    """
    Allows logged in users to create a new thread and post at the same time.
    Also, gives the option of creating a poll when creating a new thread.
    """
    subject = get_object_or_404(Subject, pk=subject_id)
    poll_subject_formset = formset_factory(
        PollSubjectForm, extra=3)  # makes a set of 3 forms in this case.

    if request.method == "POST":
        thread_form = ThreadForm(request.POST)
        post_form = PostForm(request.POST)
        poll_form = PollForm(request.POST)
        poll_subject_formset = poll_subject_formset(request.POST)

        # When calling the is_valid, the formset will validate all forms in
        # one go, so you can effectively treat them like they are one form.
        if thread_form.is_valid() and post_form.is_valid(
        ) and poll_form.is_valid() and poll_subject_formset.is_valid():
            thread = thread_form.save(
                False)  # get memory only version of the model
            thread.subject = subject
            thread.user = request.user
            thread.save()

            post = post_form.save(False)
            post.user = request.user
            post.thread = thread  # newly created thread id
            post.save()

            if request.POST.get('is_a_poll', None):
                poll = poll_form.save(False)
                poll.thread = thread
                poll.save()

                # To pull out the values from each form, loop through each one.
                # It is the same when rendering.
                for subject_form in poll_subject_formset:
                    subject = subject_form.save(False)
                    subject.poll = poll
                    subject.save()

            messages.success(request, "You have created a new thread!")

            return redirect(reverse('thread', args={thread.pk}))
    else:
        thread_form = ThreadForm()
        post_form = PostForm(request.POST)
        poll_form = PollForm()
        poll_subject_formset = poll_subject_formset()

        args = {
            'thread_form': thread_form,
            'post_form': post_form,
            'subject': subject,
            'poll_form': poll_form,
            'poll_subject_formset':
            poll_subject_formset,  # loop through the formset of 3 forms when rendering.
        }

        args.update(csrf(request))

        return render(request, 'forum/thread_form.html', args)
示例#28
0
 def test_insert_questions(self):
     questions = ['q1', 'q2']
     form = PollForm(questions)
     self.assertEqual(set(form.fields), set(questions))
示例#29
0
def create(request):
    class RequiredFormSet(BaseFormSet):
        def __init__(self, *args, **kwargs):
            super(RequiredFormSet, self).__init__(*args, **kwargs)
            for form in self.forms:
                form.empty_permitted = False

    ChoiceFormSet = formset_factory(ChoiceForm,
                                    max_num=10,
                                    formset=RequiredFormSet)
    if request.method == 'POST':  # If the form has been submitted...
        poll_form = PollForm(request.POST)  # A form bound to the POST data
        # Create a formset from the submitted data
        choice_formset = ChoiceFormSet(request.POST, request.FILES)

        if poll_form.is_valid() and choice_formset.is_valid():
            poll = poll_form.save(commit=False)
            if request.user.is_authenticated():
                poll.creator = request.user
            poll.save()
            poll_form.save_m2m()
            for form in choice_formset.forms:
                choice = form.save(commit=False)
                choice.poll = poll
                choice.save()
            top_polls = Poll.objects.annotate(
                num_votes=Sum('choice__votes')).order_by('-num_votes')
            top_tags = Poll.tags.most_common()[:10]
            all_tags = Poll.tags.most_common()
            if request.user.is_authenticated():
                auth_form = False
                logged_in = True

            else:
                logged_in = False
                auth_form = AuthenticateForm()
            return render_to_response('polls/detail.html', {
                "poll": poll,
                "top_polls": top_polls,
                "top_tags": top_tags,
                "auth_form": auth_form,
                "logged_in": logged_in,
                "all_tags": all_tags
            },
                                      context_instance=RequestContext(request))
    else:
        poll_form = PollForm()
        choice_formset = ChoiceFormSet()

    top_polls = Poll.objects.annotate(
        num_votes=Sum('choice__votes')).order_by('-num_votes')
    top_tags = Poll.tags.most_common()[:10]
    all_tags = Poll.tags.most_common()
    if request.user.is_authenticated():
        auth_form = False
        logged_in = True

    else:
        logged_in = False
        auth_form = AuthenticateForm()
    return render_to_response('polls/create.html', {
        "top_polls": top_polls,
        "top_tags": top_tags,
        "auth_form": auth_form,
        "logged_in": logged_in,
        "all_tags": all_tags,
        "poll_form": poll_form,
        "choice_formset": choice_formset
    },
                              context_instance=RequestContext(request))
示例#30
0
 def test_no_questions(self):
     form = PollForm(questions=[])
     self.assertEqual(set(form.fields), set([]))