예제 #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 non-validate form error.
        form_1 = PollForm({'choice': 1}, instance=self.poll_1)
        self.assertRaises(ValidationError, form_1.save)

        # Test the first choice.
        self.assertTrue(form_1.is_valid())
        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)
        self.assertTrue(form_2.is_valid())
        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)
        self.assertTrue(form_3.is_valid())
        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 test_form_valid_with_invalid_data(self):
     """
     Test that a form with data for 3 choices
     will not be valid if max_answers=2
     """
     form = PollForm({'choice': [1, 2, 3]}, instance=self.multi_answer_poll)
     self.assertFalse(form.is_valid())
예제 #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_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,
                   })
예제 #5
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()),
                   })
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)
예제 #7
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)
예제 #8
0
 def post(self, request, *args, **kwargs):
     form = PollForm(request.POST, instance=self.get_object())
     if form.is_valid():
         form.save()
         return HttpResponseRedirect(self.success_url)
     else:
         return render(request, self.template_name,
             {'form': form, 'poll': self.get_object()})
예제 #9
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)
예제 #10
0
파일: views.py 프로젝트: Friss/PollNation
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))
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)
예제 #12
0
def question(request):
	if request.method == 'POST':
		formulario = PollForm(request.POST)
		if formulario.is_valid():
			formulario.save()
			return HttpResponseRedirect('/polls/')
	else:
		formulario = PollForm()
	return render_to_response('pollform.html', {'formulario':formulario},
								 context_instance=RequestContext(request))
예제 #13
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
    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])})
예제 #15
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
예제 #16
0
def addPoll(request):
    if request.method == 'POST':
        form = PollForm(request.POST)    
        if form.is_valid():
            newpoll = form.save(commit =False)
            newpoll.pub_date = timezone.now()
            newpoll.save()
            return HttpResponseRedirect(reverse('polls:thanks'))#, args=(newpoll.question,))
    else:
        form = PollForm()
    return render(request, 'polls/addpoll.html', {'form': form})
예제 #17
0
def createPoll(request):
    form = PollForm(request.POST or None)
    if not form.is_valid():
        context = {}
        poll_list = Poll.objects.all()
        context['poll_list'] = poll_list
        context['form'] = form
        return render(request, 'polls/index.html', context)
    else:
        form.save()
        return HttpResponseRedirect('/polls')
예제 #18
0
def new_thread(request, subject_id):
    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 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 request.POST.get('is_a_poll', None) and 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 create 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)
    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 update(request,poll_id):
	poll = get_object_or_404(Poll,pk=poll_id)
	if request.method == "POST":
		form = PollForm(request.POST,instance=poll)
		choices_form_set = modelformset_factory(Choice,fields=('choice_text','votes',))
		form_set =choices_form_set(request.POST)
		if form.is_valid() and form_set.is_valid:
			form.save()
			form_set.save()
		return HttpResponseRedirect(reverse('polls:index'))
	else:
		context = {'form':NewPoll(poll)}
		return render(request,'polls/edit.html',context)
예제 #21
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))
예제 #22
0
파일: views.py 프로젝트: stabone/papillon
def poll_update(request):
    if request.method == "POST":
        poll_id = request.POST.get('record', '')

        info = get_object_or_404(Polls, id=poll_id)
        poll = PollForm(request.POST, instance=info)

        if poll.is_valid():
            poll.save()

            return redirect(reverse_lazy('poll_list'))

    return render(request, 'poll/form.html', {'form': poll})
예제 #23
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})
예제 #24
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)
예제 #25
0
def view_index(request):
	form = PollForm()
	if request.method == "POST":
		form = PollForm(request.POST)
		if form.is_valid():
			form.save()
			return HttpResponse("<h4>El registro se agrego correctamente</h4><br><br><a href='/'>Agregar uno nuevo</a>")
		else:
			return render_to_response("index.html",{'form':form},
				context_instance=RequestContext(request))
			
	else:
		return render_to_response("index.html",{'form':form},
			context_instance=RequestContext(request))
예제 #26
0
파일: views.py 프로젝트: stabone/papillon
def poll_create(request):
    if request.method == "GET":
        return redirect(reverse_lazy('poll_form'))

    poll_form = PollForm(request.POST)

    if poll_form.is_valid():
        poll = poll_form.save(commit=False)
        poll.user = request.user
        poll.save()

        return redirect(reverse_lazy('poll_list'))

    return render(request, 'poll/form.html', {'form': poll_form})
예제 #27
0
def vote(request, poll_id):
    poll = get_object_or_404(Poll, pk=poll_id)
    if request.method == 'POST': # If the form has been submitted...
        form = PollForm(poll_id, request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            choices = form.cleaned_data['choices']
            choices.update(votes=F('votes') + 1)
            return HttpResponse('Saved') # Redirect after POST
    else:
        form = PollForm(poll_id) # An unbound form

    return render(request, 'polls/vote.html', {
        'form': form,
        'poll': poll,
    })
예제 #28
0
def create(request):
	if request.method == 'POST':
		form = PollForm(request.POST)
		choices_form_set = modelformset_factory(Choice,fields=('choice_text','votes',))
		form_set =choices_form_set(request.POST)
		if form.is_valid() and form_set.is_valid:
			poll = form.save()
			choices = form_set.save(commit=False)
			for choice in choices:
				choice.poll_id = poll.id
				choice.save()
		return HttpResponseRedirect(reverse('polls:index'))
	else:
		context = {'form':NewPoll()}
		return render(request,'polls/new.html',context)
예제 #29
0
파일: views.py 프로젝트: mntan/testing-poll
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))
예제 #30
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))
예제 #31
0
파일: views.py 프로젝트: greyshi/djangosite
def create(request):
    if request.method == 'POST':
        form = PollForm(request.POST)
        if form.is_valid():
            poll = Poll(question=form.cleaned_data['question'])
            poll.save()
            for c in ['choice{0}'.format(i) for i in range(1, 5)]:
                try:
                    text = form.cleaned_data[c]
                except KeyError:
                    break
                if text:
                    poll.choice_set.create(choice_text=text)
            return HttpResponseRedirect('/polls/')
    else:
        form = PollForm()  # an unbound form

    return render(request, 'polls/create.html', {'form': form})
예제 #32
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)
예제 #33
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)
예제 #34
0
 def test_is_valid_with_too_many_answers(self):
     """
     Test that a form with data for 3 choices when max_answers =2
     is not valid
     """
     self.assertEqual(self.choice_31.votes, 0)
     self.assertEqual(self.choice_32.votes, 0)
     self.assertEqual(self.choice_33.votes, 0)
     form = PollForm(
         {'choice':
             [self.choice_31.id, self.choice_32.id, self.choice_33.id]},
         instance=self.multi_answer_poll)
     self.assertRaises(form.is_valid())
     choice1 = Choice.objects.get(id=self.choice_31.id)
     choice2 = Choice.objects.get(id=self.choice_32.id)
     choice3 = Choice.objects.get(id=self.choice_33.id)
     self.assertEqual(choice1.votes, 0)
     self.assertEqual(choice2.votes, 0)
     self.assertEqual(choice3.votes, 0)
예제 #35
0
def index(request):
    latest_poll_list = Poll.objects.order_by('-pub_date')[:5]
    pollform = PollForm()
    choiceform = ChoiceForm()
    if request.method == 'POST':
        pollform = PollForm(request.POST, request.FILES)
        choiceform = ChoiceForm(request.POST)
        if pollform.is_valid():
            pollform.comments = pollform.cleaned_data['comments']
            pollform.save()
        else:
            pollform = PollForm()
        if choiceform.is_valid():
            choiceform.save()
        else:
            choiceform = ChoiceForm()
    context = {'latest_poll_list': latest_poll_list, 'pollform': pollform,
               'choiceform': choiceform}
    return render(request, 'polls/index.html', context)
예제 #36
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})
def create_poll(request, template='polls/create.html'):
    ChoiceFormSet = inlineformset_factory(Poll, Choice, extra=3)
    # If initial load of the page
    if not request.POST:
        form = PollForm()
        p = Poll()
        formset = ChoiceFormSet(instance=p)
    else:
        form = PollForm(request.POST)
        p = Poll()
        formset = ChoiceFormSet(request.POST, instance=p)

        if form.is_valid():
            p = form.save()
            formset.instance = p
            if formset.is_valid():
                formset.save()

            return redirect('poll_detail', p.id)

    return render(request, template, {'form': form, 'formset': formset})
예제 #38
0
파일: views.py 프로젝트: aausch/hotdot
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)
예제 #39
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}
    )
예제 #40
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)
예제 #41
0
파일: views.py 프로젝트: tekton/DocuCanvas
from datetime import date, timedelta


@login_required
def new_poll(request):
    PollItemFormset = inlineformset_factory(Poll, PollItem, can_delete=False, extra=1)
    poll = Poll()
    try:
        projects = Project.objects.all()
    except Exception, e:
        print(e)
    if request.method == 'POST':
        print(request.POST)
        poll_form = PollForm(request.POST, instance=poll)
        formset = PollItemFormset(request.POST, instance=poll)
        if poll_form.is_valid() and formset.is_valid():
            p = poll_form.save()
            b = 0
            for a in request.POST.getlist('pollitem_set-TOTAL_FORMS'):
                if(int(a) > b):
                    b=a
            for i in range(0, int(b)):
                text = 'pollitem_set-' + str(i) + '-item'
                value = request.POST[text]
                item = PollItem(added_by=request.user, item=value, poll=poll)
                try:
                    item.save()
                except Exception, e:
                    print(e)
            poll.total_items = b
            poll.save()
예제 #42
0
def threads(request, subject_id):
    subject = get_object_or_404(Subject, pk=subject_id)
    return render(request, 'forum/threads.html', {'subject': subject}

@login_required
def new_thread(request, subject_id):
   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 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:
       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, 'thread_form.html', args)

def thread(request, thread_id):
    thread_ = get_object_or_404(Thread, pk=thread_id)
    args = {'thread': thread_}
    args.update(csrf(request))
    return render(request, 'forum/thread.html', args)

@login_required
def new_post(request, thread_id):
    thread = get_object_or_404(Thread, pk=thread_id)

    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(False)
            post.thread = thread
            post.user = request.user
            post.save()

            messages.success(request, "Your post has been added to the thread!")

            return redirect(reverse('thread', args={thread.pk}))
    else:
        form = PostForm()

    args = {
        'form' : form,
        'form_action': reverse('new_post', args={thread.id}),
        'button_text': 'Update Post'
    }
    args.update(csrf(request))

    return render(request, 'post_form.html', args)

@login_required
def edit_post(request, thread_id, post_id):
   thread = get_object_or_404(Thread, pk=thread_id)
   post = get_object_or_404(Post, pk=post_id)

   if request.method == "POST":
       form = PostForm(request.POST, instance=post)
       if form.is_valid():
           form.save()
           messages.success(request, "You have updated your thread!")

           return redirect(reverse('thread', args={thread.pk}))
   else:
       form = PostForm(instance=post)


   args = {
       'form' : form,
       'form_action': reverse('edit_post',  kwargs={"thread_id" : thread.id, "post_id": post.id}),
       'button_text': 'Update Post'
   }
   args.update(csrf(request))

   return render(request, 'forum/post_form.html', args)

@login_required
def delete_post(request, post_id):
   post = get_object_or_404(Post, pk=post_id)
   thread_id = post.thread.id
   post.delete()

   messages.success(request, "Your post was deleted!")

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

@login_required
def thread_vote(request, thread_id, subject_id):
   thread = Thread.objects.get(id=thread_id)

   subject = thread.poll.votes.filter(user=request.user)

   if subject:
       messages.error(request, "You already voted on this! ... You’re not trying to cheat are you?")
       return redirect(reverse('thread', args={thread_id}))

   subject = PollSubject.objects.get(id=subject_id)

   subject.votes.create(poll=subject.poll, user=request.user)

   messages.success(request, "We've registered your vote!")

   return redirect(reverse('thread', args={thread_id}))
예제 #43
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)
예제 #44
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))