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())
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)
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])})
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))
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 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)
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)
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')
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})
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])})
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))
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)
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})
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)
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})
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 poll_form.is_valid() and poll_subject_formset.is_valid(): if request.POST.get('is_a_poll', None): 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 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})
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))
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)
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, })
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))
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)
def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.creator = self.request.user obj.image = request.FILES.get('image') obj.save() # Without this next line the tags won't be saved. form.save_m2m() for f in request.FILES: print f for key, val in request.POST.iteritems(): if 'answer_txt_' in key: a = Answer(poll=obj, answer=val) a.save() return redirect(obj.get_absolute_url()) else: context = { 'title': _('Create new poll'), 'location': form.cleaned_data['location'], 'links': links['polls'], 'appname': 'poll-create', 'form': PollForm(request.POST), } return render(request, self.template_name, context)
def main(request): title = 'Polls' polls = Poll.filtered.open_for_user(request.user) for poll in polls: poll.form = PollForm(poll=poll, user=request.user) return TemplateResponse(request, 'polls/main.html', locals())
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)
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)
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, })
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 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})
def test_init(self): # Test successful init without data. form = PollForm(instance=self.poll_1) self.assertTrue(isinstance(form.instance, Poll)) self.assertEqual(form.instance.pk, self.poll_1.pk) self.assertEqual([c for c in form.fields['choice'].choices], [(1, u'Yes'), (2, u'No')]) # Test successful init with data. form = PollForm({'choice': 3}, instance=self.poll_2) self.assertTrue(isinstance(form.instance, Poll)) self.assertEqual(form.instance.pk, self.poll_2.pk) self.assertEqual([c for c in form.fields['choice'].choices], [(3, u'Alright.'), (4, u'Meh.'), (5, u'Not so good.')]) # Test a failed init without data. self.assertRaises(KeyError, PollForm) # Test a failed init with data. self.assertRaises(KeyError, PollForm, {})
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)
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)
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)
def get(self, request, *args, **kwargs): slug = kwargs['slug'] location = Location.objects.get(slug=slug) ctx = { 'title': _('Create new poll'), 'location': location, 'links': links['polls'], 'appname': 'poll-create', 'form': PollForm(initial={'location': location}) } return render(request, self.template_name, ctx)
def 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})
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)
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})
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 get(self, request, *args, **kwargs): context = super(PollVoteView, self).get_context_data(**kwargs) # get a Poll instance from the db and add it to the context poll_id = kwargs.get('poll_id') poll = get_object_or_404(Poll, pk=poll_id) context['poll'] = poll # add poll form to the context questions = [field.title for field in poll.template.fields] context['form'] = PollForm(questions=questions) return self.render_to_response(context)
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} )
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()))
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_get(request, subject, poll_subject_formset): thread_form = ThreadForm() post_form = PostForm(request.POST) poll_form = PollForm() poll_subject_formset = poll_subject_formset() args = { 'thread_form': thread_form, 'post_form': post_form, 'subject': subject, 'poll_form': poll_form, 'poll_subject_formset': poll_subject_formset } args.update(csrf(request)) return render(request, 'forum/thread_form.html', args)
def neighborhood_home(request): if request.method == 'POST': report_form = ReportForm(request.POST) if report_form.is_valid(): report = report_form.save() report.sender = request.user report.time = timezone.now() report.save() report_form = ReportForm() announcement_form = AnnouncementForm() pollform = PollForm() neighborhood = request.user.userprofile.house.neighborhood request.session['neighborhood_id'] = neighborhood.id feed = Feed.objects.get(neighborhood=neighborhood) feedposts = get_recent_posts(feed.id) eventform = EventForm() request.session['feed_id'] = feed.id user_prof = request.user.userprofile # return the 20 most recent activities from the user activities = Activity.objects.filter( user=request.user).order_by('date')[:20] # return the 20 most recent user messages messages = Message.objects.filter( receiver=request.user).order_by('time')[:20] board_permissions = user_prof.is_board_member() polls = Poll.objects.filter( neighborhood=neighborhood, pub_date__lte=timezone.now()).order_by('-pub_date') markers = Marker.objects.all().filter(neighborhood_id=neighborhood.id) return render( request, 'neighborhood/map_home.html', { 'neighborhood': neighborhood, 'user': user_prof, 'activities': activities, 'messages': messages, 'markers': markers, 'feedposts': feedposts, 'report_form': report_form, 'announcement_form': announcement_form, 'pollform': pollform, 'eventform': eventform, 'board_permissions': board_permissions, 'polls': polls })
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)
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 test_poll_form_question_field_label(self): form = PollForm() self.assertTrue( form.fields['question_text'].label == None or form.fields['question_text'].label == 'Question text')
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)
def get_form(self): """Get the form to create or update a poll.""" return PollForm(type=PollType.MANUAL.name)
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)
def test_insert_questions(self): questions = ['q1', 'q2'] form = PollForm(questions) self.assertEqual(set(form.fields), set(questions))
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 test_no_questions(self): form = PollForm(questions=[]) self.assertEqual(set(form.fields), set([]))