Ejemplo n.º 1
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()})
    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])})
Ejemplo n.º 3
0
 def test_save(self):
     """
     Test that saving with max_answer=1 works
     """
     self.assertEqual(self.poll_1.choices.get(id=1).votes, 0)
     self.assertEqual(self.poll_1.choices.get(id=2).votes, 0)
     form = PollForm({'choice': self.choice_11.id}, instance=self.poll_1)
     form.save()
     self.assertEqual(self.poll_1.choices.get(id=1).votes, 1)
     self.assertEqual(self.poll_1.choices.get(id=2).votes, 0)
Ejemplo n.º 4
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
Ejemplo n.º 5
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))
Ejemplo n.º 6
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')
Ejemplo n.º 7
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))
Ejemplo n.º 8
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)
Ejemplo n.º 9
0
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})
Ejemplo n.º 10
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))
Ejemplo n.º 11
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))
Ejemplo n.º 12
0
 def test_save_with_one_answer_for_multi_answer_poll(self):
     """
     Test that you can still save with data for 1 choice when max_answers=2
     """
     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]}, instance=self.multi_answer_poll)
     form.save()
     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, 1)
     self.assertEqual(choice2.votes, 0)
     self.assertEqual(choice3.votes, 0)
Ejemplo n.º 13
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)
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)
Ejemplo n.º 15
0
 def test_save_with_multiple_answers(self):
     """
     Test saving two answers is valid when max_answers=2
     """
     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]},
         instance=self.multi_answer_poll)
     form.save()
     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, 1)
     self.assertEqual(choice2.votes, 1)
     self.assertEqual(choice3.votes, 0)
Ejemplo n.º 16
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))
Ejemplo n.º 17
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))
Ejemplo n.º 18
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)
Ejemplo n.º 20
0
 def test_save_too_many_answers(self):
     """
     Try to save a form with data for 3 choices when max_answers =2
     """
     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)
     with self.assertRaises(forms.ValidationError):
         form.save()
     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)
Ejemplo n.º 21
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)
Ejemplo n.º 22
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)
Ejemplo n.º 23
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})
Ejemplo n.º 24
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)
Ejemplo n.º 25
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)
Ejemplo n.º 26
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)
Ejemplo n.º 27
0
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})
Ejemplo n.º 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)
Ejemplo n.º 29
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)
Ejemplo n.º 30
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)
Ejemplo n.º 31
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)
Ejemplo n.º 32
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})
Ejemplo n.º 34
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)
Ejemplo n.º 35
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}
    )
Ejemplo n.º 36
0
def create(request):

    if request.POST:
        form = PollForm(request.POST)
        poll = form.save(commit=False)
        poll.muaccount = request.muaccount
        poll.pub_date = datetime.datetime.now()
        poll.save()
        if request.POST["choice1"]:
            c1 = Choice()
            c1.poll = poll
            c1.choice = request.POST["choice1"]
            c1.votes = 0
            c1.save()
        if request.POST["choice2"]:
            c2 = Choice()
            c2.poll = poll
            c2.choice = request.POST["choice2"]
            c2.votes = 0
            c2.save()
        if request.POST["choice3"]:
            c3 = Choice()
            c3.poll = poll
            c3.choice = request.POST["choice3"]
            c3.votes = 0
            c3.save()
        if request.POST["choice4"]:
            c4 = Choice()
            c4.poll = poll
            c4.choice = request.POST["choice4"]
            c4.votes = 0
            c4.save()

        return HttpResponseRedirect(reverse("polls.views.index"))
    else:
        form = PollForm()
        return render_to_response("polls/create.html", {"form": form}, RequestContext(request, locals()))
Ejemplo n.º 37
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)
Ejemplo n.º 38
0

@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()
            print('saving form')
Ejemplo n.º 39
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)
Ejemplo n.º 40
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}))
Ejemplo n.º 41
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))