def ask(request): if request.method == 'POST': form = QuestionForm(request.POST) if form.is_valid(): question = form.save(commit=False) if request.user.is_authenticated(): question.user = request.user question.save() return render(request, 'ask_librarian/frontend/thanks.html', { 'question': question, }) else: if request.user.is_authenticated(): form = QuestionForm( initial={ 'fio': request.user.last_name + u' ' + request.user.first_name, 'email': request.user.email, } ) else: form = QuestionForm() return render(request, 'ask_librarian/frontend/ask.html', { 'form': form })
def main(): error = None form = QuestionForm() if request.method == 'POST': if form.validate_on_submit(): newName = form.name.data newEmail = form.email.data newQuestion = form.question.data new_question = Question( newName, newEmail, newQuestion ) msg = Message("Your question submitted", recipients = [newEmail], sender = '*****@*****.**', body = u'Hello {}\n Your question was submitted through the site frenchonline. We will answer it ASAP ! '.format(newName) ) admin_msg = Message ("You have a new question", recipients = ['*****@*****.**'], sender = '*****@*****.**', body = u'Your contact {} asked a question with the content \n----------\n"{}"\n----------\n, \nPlease answer through this email {}'.format(newName, newQuestion, newEmail) ) db.session.add(new_question) db.session.commit() mail.send(msg) mail.send(admin_msg) return render_template('index.html', form = form, error = error)
def add_question(request): context = {} settings = Settings.get_by_user(request.user) initial = {} if settings.group: initial["groups"] = [settings.group.id] if request.method == "POST": form = QuestionForm(request.POST) if form.is_valid(): question = form.save(commit=False) question.added_by = request.user question.save() revision = QuestionRevision( question=question, user=request.user, text=form.cleaned_data["body"], active=True) revision.save() return HttpResponseRedirect("/question/%s" % question.id) else: form = QuestionForm(initial=initial) context["form"] = form return r2r(request, "add_question", context)
def question_add(): # was form posted? if request.method == 'POST': form = QuestionForm(request.form) if form.validate_on_submit(): question = Question( title=request.form['title'], text=request.form['text'], date=datetime.now(), user_id=current_user.id) # Answer save in db db.session.add(question) db.session.commit() return redirect(url_for('index')) else: # Show errors in form flash_errors(form) else: form = QuestionForm() return render_template('question_add.html', form=form)
def post_question(): """Post a question""" if not g.user: flash("Log in required", "warning") return redirect('/login') form = QuestionForm() if request.method == 'POST': if not g.user: flash("Log in required", "warning") return redirect('/login') if form.validate_on_submit(): subject = Subject.query.filter_by(name=form.subject.data).first() question = Question(subjectID=subject.id, title=form.title.data, content=form.content.data, authorID=g.user.id, hashtag=form.hashtag.data) db.session.add(question) db.session.commit() return redirect(f'/q/{question.subject.name}') return render_template('board/ask.html', form=form)
def question_edit(request, id=None): if id is not None: question = get_object_or_404(Question, pk=id) else: question = None categs = [(c.name.capitalize(), c.name) for c in Category.objects.all()] if request.method == 'POST': form = QuestionForm(request.POST, instance=question) if form.is_valid(): newq = form.save() if (newq.endorsed_by is None): newq.endorsed_by = request.user newq.save() return HttpResponseRedirect(reverse('wouso.interface.cpanel.views.qpool_home', args = (newq.category.name,))) else: show_users = False if question: if question.category: if question.category.name == 'proposed': show_users = True form = QuestionForm(instance=question, users=show_users) return render_to_response('cpanel/question_edit.html', {'question': question, 'form': form, 'module': 'qpool', 'categs': categs}, context_instance=RequestContext(request))
def new_question(): """Creates a new question""" form = QuestionForm() if request.method == 'POST' and form.validate_on_submit(): question = Question( content=form.content.data, added_by=users.get_current_user(), location=get_location(form.location.data) ) try: question.put() question_id = question.key.id() create_nearby_question(question_id) flash(u'Question %s successfully saved.' % question_id, 'success') add_question_to_search_index(question) return redirect(url_for('list_questions_for_user')) except CapabilityDisabledError: flash(u'App Engine Datastore is currently in read-only mode.', 'info') return redirect(url_for('list_questions_for_user')) else: flash_errors(form) return redirect(url_for('list_questions_for_user'))
def post_detail(id): post = Post.query.get(id) post.text = Markup(post.text) render_url = post.custom_html_file if post.custom_html_file else 'post_detail.html' if post.is_practice: questions = post.questions questions.sort(key=lambda x: x.sorting_column) qid, current_question = _set_qid_and_current_question( request.args.get('qid'), questions) form = QuestionForm(current_question) if request.method == 'POST': if form.validate_on_submit(): user_answer = request.form['user_answer'] if user_answer == current_question.answer: is_final = qid == len(questions) if is_final: flash( 'Вы ответили на последний вопрос блока, congrats!') return redirect(url_for('index')) return redirect(url_for('post_detail', qid=qid + 1, id=id)) else: form, qid = None, None return render_template(render_url, post=post, form=form, qid=qid)
def quiz(): if current_user.is_authenticated: form = QuestionForm() if form.validate_on_submit(): question = Question.query.get(form.question_id.data) answers = [answer.content.lower().replace(' ', '') for answer in question.answers] input_answer = form.answer.data.lower().replace(' ', '') check = [levenshteinDistance(input_answer, answer) < 3 for answer in answers] if True in check: db.session.add(Correct(user_id=current_user.id, question_id=question.id)) db.session.commit() flash("Correct Answer") else: flash("Wrong Answer") all_questions = set(Question.query.all()) answered_already = {correct.question for correct in Correct.query.filter_by(user_id=current_user.id).all()} unanswered = all_questions.difference(answered_already) if len(unanswered) == 0: flash("Well Done!! You have already answered all the questions we have") return redirect(url_for('home')) question = random.choice(list(unanswered)) number = question.id form.question_id.process_data(number) return render_template("quiz.j2", question=question, form=form, title=f"quiz - {number}") else: flash("Cant play without login") return redirect(url_for('login'))
def send_newsletter(): form = QuestionForm() if request.method == 'POST': recievers = Newsletter.query.order_by(Newsletter.id.desc()).all() if form.validate() == False: flash('Wymagane wszystkie pola.') return render_template('admin/send_newsletter.html', form=form) else: msg = Message(sender=("*****@*****.**")) for reciever in recievers: msg.add_recipient(reciever.email) msg.subject = " %s " % (form.subject.data) msg.body = """ %s Aby wypisac sie z tego newslettera wejdz w zakladke pomoc na naszej stronie. """ % (form.message.data) mail.send(msg) print 'Newsletter do %s zostal wyslany' % (msg.recipients) flash('Newsletter zostal wyslany.') return redirect('/admin/newsletter') elif request.method == 'GET': print 'ok' return render_template('admin/send_newsletter.html', form=form, title='Wysylanie newslettera')
def createQuestion(request, poll_id): if (poll_id == None): return redirect("/") poll = Poll.objects.get(id=poll_id) if (poll.creator != request.user): return redirect("/") if request.method == "POST": question_form = QuestionForm(data=request.POST) if question_form.is_valid(): #falta validar por la respuesta. question = question_form.save(commit=False) question.poll = Poll.objects.get(id=poll_id) type = Type.objects.get(id=1) question.type = type question.save() for ans in request.POST.getlist('answers'): answer = Answer(question=question, text=ans) answer.save() if request.POST['continuar'] == "1": return render_to_response( "create_question.html", context_instance=RequestContext(request)) else: return redirect('/invitation_list/' + poll_id) return render_to_response("create_question.html", {'poll': poll}, context_instance=RequestContext(request))
def SaveQuestionForm(request): if request.is_ajax(): data = request.POST.copy() faq_form = QuestionForm(data) if faq_form.is_valid(): saved_object = faq_form.save() subject = u'%s - Новый вопрос' % settings.SITE_NAME subject = u''.join(subject.splitlines()) message = render_to_string( 'faq/admin_message_template.html', { 'saved_object': saved_object, 'site_name': settings.SITE_NAME, } ) try: emailto = Settings.objects.get(name='workemail').value except Settings.DoesNotExist: emailto = False if emailto: msg = EmailMessage(subject, message, settings.DEFAULT_FROM_EMAIL, [emailto]) msg.content_subtype = "html" msg.send() return HttpResponse('success') else: faq_form_html = render_to_string( 'faq/faq_form.html', {'form': faq_form} ) return HttpResponse(faq_form_html) else: return HttpResponseBadRequest()
def edit_question(request, question_id): a_question = get_object_or_404(Question, pk=question_id) form = QuestionForm (request.POST or None, instance = a_question) if form.is_valid(): question = form.save() return redirect(reverse("polls:index")) return render (request, "polls/edit_template.html", {'form': form })
def add_question(): form = QuestionForm() if form.validate_on_submit(): add_question = Questions(question=request.form['question'], user_id=g.user.id) db_session.add(add_question) db_session.commit() flash('Question Add!') return redirect(url_for('questions')) return render_template('add_question.html', title='Add question', form=form)
def add_new_question(request): if request.POST: form = QuestionForm(request.POST) if form.is_valid(): new_question = form.save() # return HttpResponseRedirect('/question/updated/%s/' %(new_question.id)) return HttpResponseRedirect('/question/show/') else: form = QuestionForm() return render_to_response('question_model_form.html', dict(form=form))
def add_question(request): form = QuestionForm() if request.method == 'POST': form = QuestionForm(request.POST) if form.is_valid(): form.instance.user = request.user form.save() return HttpResponseRedirect(reverse('index')) return request_response(request, 'answers/add_question.html', {'form':form})
def ask_question(request, project_id): proj = Project.objects.get(id=int(project_id)) form = QuestionForm(request.POST) if form.is_valid(): new_question = Question(text=form.cleaned_data["question"], project=proj, asker=request.user, reply="") new_question.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def index(): form = QuestionForm() if form.validate_on_submit(): question = Question(body=form.question.data, voite=None) db.session.add(question) db.session.commit() flash('Question was added') return redirect(url_for('index')) questions_all = Question.query.all() return render_template('index.html', title='Home', form=form, questions=questions_all)
def question_entry(request): '''Submit question/answer pairs''' args = {} args["added"] = False if request.method == 'POST': question_form = QuestionForm(request.POST) if question_form.is_valid(): question_form.save() args["added"] = True args["prev_question"] = str(question_form.instance.question) args["prev_topic"] = str(question_form.instance.subtopic) # clear form so next question can be entered. question_form = QuestionForm() else: question_form = QuestionForm() args["question_form"] = question_form return render_to_response( 'questionEntry.html', args, context_instance=RequestContext(request), )
def create(request): if request.method == 'POST': form = QuestionForm(request.POST) if form.is_valid(): form.save() mail_admins('Someone made a question!', 'http://' + request.get_host() + '/admin/quiz/question/?state=NEW') return HttpResponseRedirect('/quiz/created') else: form = QuestionForm() return render(request, 'quiz/create.html', {'form':form, 'title':'Create question'})
def create(request): if request.method == 'POST': form = QuestionForm(request.POST) if form.is_valid(): form.save() return redirect('index') else: form = QuestionForm() return render_to_response('questionsandanswers/create.html', {'form': form}, context_instance=RequestContext(request))
def add_question(request, quiz_id): """Add the new question that superuser created to the database.""" form = QuestionForm(request.POST) if form.is_valid(): new_ques = form.save() new_ques.save() return HttpResponseRedirect( reverse('create_question', kwargs={'quiz_id': quiz_id})) else: return render(request, 'invalidAttempt.html', {'message': 'Invalid input!'})
def question_admin(request, slug): q = get_object_or_404(Question, slug=slug) if request.method == 'POST': form = QuestionForm(request.POST, request.FILES, instance=q) if form.is_valid(): return HttpResponseRedirect(form.save().get_absolute_url()) else: form = QuestionForm(instance=q) return render_to_response('qna/admin.html', { 'question':q, 'form':form, }, context_instance=RequestContext(request))
def addQuestion(request): if request.method == "POST": form = QuestionForm(request.POST) if form.is_valid(): newQuestion = Question(course_id = form.cleaned_data['course_id'], student_id = form.cleaned_data['student_id'], title = form.cleaned_data['title'], content = form.cleaned_data['content']) newQuestion.post_time = str(datetime.datetime.now()).split('.')[0] newQuestion.save() return HttpResponseRedirect('/admin') else: form = QuestionForm() return render(request, 'polls/addQuestion.html', {'form': form})
def add_question(): #Pass form to template form = QuestionForm() if form.validate_on_submit(): #save data to db data = Question(question=form.question.data) db.session.add(data) db.session.commit() return redirect(url_for('index')) return render_template('add_question.html', form=form)
def ask(): if 'email' not in session: return redirect(url_for('signin')) form = QuestionForm() if form.validate_on_submit(): question = Question(form.question.data, User.query.filter_by(email=session['email']).first()) db.session.add(question) db.session.commit() flash('Successfully added question !') return redirect(url_for('index')) return render_template('ask.html', form=form)
def qs_ask_page(request): if request.method == 'POST': qform = QuestionForm(request.POST); if qform.is_valid(): ctrls.saveQuestionByForm(request,qform); return HttpResponseRedirect("/question/quest/") else: if request.user.is_authenticated(): quest_types = Question_Type.objects.all(); #@UndefinedVariable return render_to_response('faqs_ask.html', {'quest_types':quest_types},context_instance=RequestContext(request)) else: return HttpResponseRedirect("/login/")
def create(request): if request.method == "POST": form = QuestionForm(request.POST) if form.is_valid(): form.save() mail_admins( "Someone made a question!", "http://" + request.get_host() + "/admin/quiz/question/?published__exact=0" ) return HttpResponseRedirect("/quiz/created") else: form = QuestionForm() return render_to_response("quiz/create.html", {"form": form}, context_instance=RequestContext(request))
def create(): data = request.get_json() form = QuestionForm(**data) if form.validate(): form_data = form.data form_data['ip'] = request.remote_addr question = g.user.create_question(**form_data) return jsonify({"data": question.json_data()}) else: return json_error(type="VALIDATION_FAILED", messages=form.errors)
def edit(request, question_id): question = get_object_or_404(Question, pk=question_id) if request.method == 'POST': form = QuestionForm(request.POST, instance=question) if form.is_valid(): form.save() return redirect('index') else: form = QuestionForm(instance=question) return render_to_response('questionsandanswers/edit.html', {'form': form}, context_instance=RequestContext(request))
def ask_question(): form = QuestionForm() if form.validate_on_submit(): question = Question(text=form.question.data, user_id=g.user.id, timestamp=datetime.datetime.utcnow()) db.session.add(question) db.session.commit() flash('New_question has been created') return render_template('ask_question.html', title = 'Sign In', form = form)
def add(): form = QuestionForm(request.form) if form.validate_on_submit(): question = Question(text=form.text.data, date=datetime.utcnow(), owner=current_user) db.session.add(question) db.session.commit() flash(gettext('Your question succesfully posted'), 'success') return redirect(url_for('questions')) return render_template('add_question.html', form = form)
def create_question(request, question_id=None): '''create or update a answer based on a question id''' user = request.user if request.POST: #save form question=None question_id = request.POST["question_id"] if question_id: #editing question=Question.objects.get(id=question_id) form = QuestionForm(request.POST, instance=question) if form.is_valid(): author = user.username question=form.save(commit=False) question.author = user question.save() currentTags=question.tags.all() for eachTag in currentTags: question.tags.remove(eachTag) tags=request.POST['tags'] if tags: tags=tags.split(",") print >>sys.stderr, repr(tags) for eachTag in tags: thisTag=Tag.objects.filter(text=eachTag) if not thisTag: #new tag tag = Tag(text=eachTag.strip()) tag.save() else: #old tag tag=thisTag[0] question.tags.add(tag) return HttpResponseRedirect('/hello/question/%s'%question.id) else: #show form args={} question=None tags="" if question_id: #editing current question=Question.objects.get(id=question_id) args['question']=question args['command']="Update" tags=",".join(question.tags.values_list("text", flat=True)) else: args['command']="Create" form = QuestionForm(tags=tags, instance=question) args['form'] = form return render_to_response("create_question.html", args, context_instance=RequestContext(request))
def questionbuilder(request): if request.method == "POST": form = QuestionForm(request.POST) if form.is_valid(): # Add tag section to form. # The tag section will be parsed, and the question will be tagged with the tags recognized. # Any unrecognized tags will be created and put into the tag table. Then the question will # tagged with these. return HttpResponseRedirect("/questionbuilder/successful/") else: form = QuestionForm() return render_to_response("testgenerator.html", {"form": form}, context_instance=RequestContext(request))
def create_question(request): form = QuestionForm(request.POST or None) #choice_form = ChoiceForm(request.POST or None) if form.is_valid(): #and choice_form.is_valid(): #choice = choice_form.save(commit=False) question = form.save(commit=False) question.pub_date = timezone.now() question.save() #choice.question = question #choice.save() return redirect(reverse("polls:index")) return render(request, 'polls/my_template.html', {'form':form,})# 'choice_form':choice_form})
def create(request): if request.method == 'POST': form = QuestionForm(request.POST) if form.is_valid(): form.save() mail_admins('Someone made a question!', 'http://' + request.get_host() + '/admin/quiz/question/?published__exact=0') return HttpResponseRedirect('/quiz/created') else: form = QuestionForm() return render_to_response('quiz/create.html', {'form':form, 'title':'Create question'}, context_instance=RequestContext(request) )
def edit_question(question_id): """Edit a question.""" question = Question.get_by_id(question_id) form = QuestionForm(obj=question) user = users.get_current_user() if request.method == "POST": if form.validate_on_submit(): question.content=form.data.get('content') question.location=form.data.get('location') question.put() flash(u'Question %s successfully modified.' % question_id, 'success') return redirect(url_for('list_questions_for_user')) return render_template('edit_question.html', question=question, form=form, user=user)
def edit_question(request, question_id): context = {} question = Question.objects.get(pk=question_id) old_revision = question.get_active_revision() if request.method == "POST": form = QuestionForm(request.POST, instance=question) if form.is_valid(): form.save() question = form.save() if old_revision.text != form.cleaned_data["body"]: new_revision = QuestionRevision(question=question, user=request.user, text=form.cleaned_data["body"], active=True) new_revision.save() old_revision.active = False old_revision.save() return HttpResponseRedirect("/question/%s" % question_id) else: form = QuestionForm(instance=question, initial={"body": old_revision.text}) context["form"] = form return r2r(request, "edit_question", context)
def ask(request): if request.method == "POST": user = request.user form = QuestionForm(request.POST) if form.is_valid(): title = form.cleaned_data['name'] tag_name = form.cleaned_data['tag'] description = form.cleaned_data['description'] tag = Tag.objects.create(tag=tag_name) question = Question.objects.create(title=title, description=description, asker=user) question.tags.add(tag) return redirect('polls:question', question_id=question.id) return render_to_response('ask.html', context=RequestContext(request))
def ajax_suggest(request): if request.method == 'POST': form = QuestionForm(request.POST) if form.is_valid(): q = Question(question=form.cleaned_data['question'], twitter_user=form.cleaned_data['twitter_user'], approved=False) q.save() message = "success" else: # shouldn't be reached accept if HTML5 validation is bypassed message = "form not valid" else: message = "you must post" return HttpResponse(message)
def add_question(): form = QuestionForm() if request.method == 'GET': return render_template("forum/add_question.html", form=form) else: try: from app import db from models import Question, Topic #if current_user.is_authenticated(): topic_list = [request.form['tags']] topics = [ ] for topic_name in topic_list: t = Topic.query.filter_by(name=topic_name).all() print t if t != []: topics.append(t[0]) question = Question(request.form['question'], request.form['description'], topics) print request.form db.session.add(question) db.session.commit() except Exception as e: print str(e) finally: return return render_template("index.html")
def render_template(request, template, params): params['twitter_account'] = settings.TWITTER_USER # Deal with Form submission which is on everypage #params['form'] = handle_form(request) params['form'] = QuestionForm() return render_to_response(template, params, context_instance=RequestContext(request))
def add_question_submission(): try: form = QuestionForm() if form.validate_on_submit(): question = Question(question_text=request.form['question_text'], answer=request.form['answer'], difficulty=request.form['difficulty'], category=request.form['category'], author=current_user._get_current_object()) db.session.add(question) db.session.commit() flash('Your question has been added.') return redirect(url_for('get_questions')) except: flash('An error occurred. Your question could not be added.') return redirect(url_for('get_questions'))
def question(request): """ Handle question :param request: :return: """ if request.method == 'POST': form = QuestionForm(request.POST) if form.is_valid(): if 'name' in form.cleaned_data: name = form.cleaned_data['name'] else: name = None if 'email' in form.cleaned_data: email = form.cleaned_data['email'] else: email = None if 'phone' in form.cleaned_data: phone = form.cleaned_data['phone'] else: phone = None if email == "" and phone == "": return JsonResponse({"result": "error"}) if 'question' in form.cleaned_data: question = form.cleaned_data['question'] else: question = None Question.objects.create( name=name, email=email, phone=phone, datetime=timezone.now(), question=question, ) try: send_mail( "New question", 'Phone: ' + phone + '\n \nEmail: ' + email, getattr(settings, "EMAIL_HOST_USER", None), [settings.EMAIL_ADDRESS, ], fail_silently=False, ) except: pass return JsonResponse({"result": "ok"}) else: return JsonResponse({"result": "error"})
def qpool_new(request, cat=None): form = QuestionForm() categs = [(c.name.capitalize(), c.name) for c in Category.objects.all()] if request.method == "POST": question = QuestionForm(data=request.POST) if question.is_valid(): newq = question.save() return redirect('qpool_home', cat=newq.category.name) else: form = question return render_to_response('cpanel/qpool_new.html', { 'form': form, 'module': 'qpool', 'categs': categs }, context_instance=RequestContext(request))
def course_lesson(self, course_title, lesson_title): data = {} data['QForm'] = QuestionForm() data['loggedIn'] = False data['loggedIn'] = True data['student'] = session['student'] data['course_lessons'] = [] data['lesson_questions'] = [] student_id = ObjectId(session['student']['id']) course = self.newCourse.get_course_by_title(course_title) fields = {"course_id":course['_id'], "title":lesson_title} lesson = self.newLesson.get_lesson(fields) subscribed = self.newStudent_subscription.get_student_course_subscriptions(student_id, lesson['course_id']) free_lessons = self.newLesson.get_free_lessons(lesson['course_id']) if ((subscribed) or (lesson['_id'] in free_lessons)): #course = self.newCourse.get_course_by_id(lesson['course_id']) similar_courses = self.newCourse_interest.get_similar_courses(course['_id']) instructor = self.newInstructor.get_instructor_by_id(course['instructor_id']) courseLessons = self.newLesson.get_lesson_by_courseId(course['_id']) lesson_questions = self.newStudent_question.get_lesson_questions(str(lesson['_id'])) if lesson_questions.count() > 0: for quest in lesson_questions: question = {} question['student'] = self.newStudent.get_student_by_id(quest['student_id'])['name'] question['date_asked'] = str(quest['date_asked']) question['quest'] = quest question['responses'] = self.newQuestion_response.get_question_responses(str(quest['_id'])) data['lesson_questions'].append(question) courseDuration = 0 n = 0 nxt = 0 prev = '' for courseLesson in courseLessons: n = n + 1; if nxt == 1: lesson['nxt'] = courseLesson['title'] nxt = 0 if courseLesson['title'] == lesson['title']: lesson['prev'] = prev nxt = 1 prev = courseLesson['title'] courseDuration = int(courseDuration) + int(courseLesson['duration']) data['course_lessons'].append(courseLesson) data['course'] = course data['lesson'] = lesson data['instructor'] = instructor data['course_duration'] = courseDuration data['similar_courses'] = similar_courses #return jsonify(len(similar_courses)) return render_template("course_lesson.html", data=data) else: return redirect(url_for('dashboard'))
def db_insert_q(): if 'user_id' and 'user_email' not in session: return redirect('/') form = QuestionForm() if form.validate_on_submit(): question = Question() question.q_user_id = session['user_id'] question.subject = form.data.get('subject') question.topic = form.data.get('topic') question.content = form.data.get('content') dbb.session.add(question) dbb.session.commit() return render_template('qeustion_success.html', name=session['user_email']) return render_template('question_make.html', form=form, user_email=session['user_email'])
def ask(request): if request.method == 'POST': instance=Student.objects.get(email_id=request.user.email) form = QuestionForm(request.POST) if form.is_valid(): uploader=request.user.first_name+" "+request.user.last_name question_text=request.POST.get('question_text','') additional_info=request.POST.get('additional_info','') now = datetime.datetime.now() for_school=instance.school_name for_class=instance.class_name show=True obj = Question(uploader=uploader, question_text=question_text,pub_date=now,additional_info=additional_info,for_class=for_class,for_school=for_school,show=show) obj.save() return index(request) else: print form.errors return index(request)
def question(): cat_id = request.args.get('cat_id') form = QuestionForm() clues = display_clue(cat_id) filtered_clues = clues if form.validate_on_submit(): value = form.value_dropdown.data filtered_clues = [] for clue in clues: print(type(clue['value']), type(value)) if clue['value'] == int(value): filtered_clues.append(clue) if len(filtered_clues) == 0: flash("No clues of value: " + value, 'danger') return render_template('question.html', clues=filtered_clues, form=form)
def edit_question_form(question_id): form = QuestionForm() question = Question.query.get_or_404(question_id) form.question_text.data = question.question_text form.answer.data = question.answer form.category.data = question.category form.difficulty.data = question.difficulty return render_template('edit_question.html', form=form, questions=[question])
def create_question(): data = request.get_json() form = QuestionForm(MultiDict(mapping=data)) if not form.validate(): return bad_request_error(form.errors) question = Question(question=form.question.data, answer=form.answer.data, difficulty=form.difficulty.data, category=form.category.data) db.session.add(question) db.session.commit() return_data = { 'id': question.id, 'question': question.question, 'answer': question.answer, 'difficulty': question.difficulty, 'category': question.category } return jsonify(return_data), 201
def new_question(): """Get user's officials and handle creating new question""" if not g.user: flash("Access unauthorized.", "danger") return redirect("/") form = QuestionForm() if form.validate_on_submit(): new_question = Question(user_id=session[CURR_USER_KEY], official_id=form.official.data, text=form.text.data) db.session.add(new_question) db.session.commit() flash("Your question has been asked!", "success") return redirect('/') form.official.choices = [(o.id, f'{o.name} ({o.office})') for o in g.user.city.officials] return render_template('questions/new_question.html', form=form)
def ask_question(self): form = QuestionForm() student_id = ObjectId(session['student']['id']) if form.validate() == False: errors = '' if form.question.errors: for error in form.question.errors: errors += ' '+error return json.dumps({'status':'ERROR','message':errors}); else: question = request.form['question'] lesson_id = request.form['lesson_id'] course_id = request.form['course_id'] result = self.newStudent_question.add(lesson_id, course_id, student_id, question) if(result == 'OK'): return json.dumps({'status':'OK'}); if(result == 'ERROR'): return json.dumps({'status':'ERROR'});
def propose(request): MAX_ANSWERS = 6 if request.method == 'POST': form = QuestionForm(nr_ans=MAX_ANSWERS, data=request.POST) if form.is_valid(): # create and save the question qdict = {} qdict['text'] = form.cleaned_data['text'] qdict['answer_type'] = form.cleaned_data['answer_type'] qdict['proposed_by'] = request.user qdict['category'] = Category.objects.filter(name='proposed')[0] q = Question(**qdict) q.save() tag = Tag.objects.filter(name=form.cleaned_data['category'])[0] q.tags.add(tag) # add the tags for tag_name in form.cleaned_data['tags']: tag = Tag.objects.filter(name=tag_name)[0] q.tags.add(tag) q.save() # add the answers for i in range(form.nr_ans): ansdict = {} if not form.cleaned_data['answer_%d' % i]: continue ansdict['text'] = form.cleaned_data['answer_%d' % i] ansdict['correct'] = form.cleaned_data['correct_%d' % i] ans = Answer(question=q, **ansdict) ans.save() return render_to_response('qproposal/thanks.html', context_instance=RequestContext(request)) else: form = QuestionForm(MAX_ANSWERS) return render_to_response('qproposal/propose.html', {'form': form}, context_instance=RequestContext(request))
def qpool_edit(request, id): question = get_object_or_404(Question, pk=id) categs = [(c.name.capitalize(), c.name) for c in Category.objects.all()] if request.method == 'POST': form = QuestionForm(request.POST, instance=question) if form.is_valid(): newq = form.save() newq.proposed_by = request.user if newq.endorsed_by is None: newq.endorsed_by = request.user newq.save() return redirect('qpool_home', cat=newq.category.name) else: print "nevalid" else: show_users = False if question: if question.category: if question.category.name == 'proposed': show_users = True form = QuestionForm(instance=question) return render_to_response('cpanel/qpool_edit.html', {'question': question, 'form': form, 'module': 'qpool', 'categs': categs}, context_instance=RequestContext(request))
def add_question(request): context = {} settings = Settings.get_by_user(request.user) initial = {} if settings.group: initial["groups"] = [settings.group.id] if request.method == "POST": form = QuestionForm(request.POST) if form.is_valid(): question = form.save(commit=False) question.added_by = request.user question.save() revision = QuestionRevision(question=question, user=request.user, text=form.cleaned_data["body"], active=True) revision.save() return HttpResponseRedirect("/question/%s" % question.id) else: form = QuestionForm(initial=initial) context["form"] = form return r2r(request, "add_question", context)