def new_question(request): context = {} if request.method == 'POST': form = QuestionForm(request.POST) if form.is_valid(): users_question = form.cleaned_data['question'] question_tags = form.cleaned_data['tags'].split(',') user_email = request.session['user_email'] user = User.objects.get(email=user_email) current_question = Question.objects.create(question=users_question, asked_by=user) current_question.save() for current_tag in question_tags: if not Tag.objects.filter(tag_name=current_tag).exists(): my_tag = Tag.objects.create(tag_name=current_tag) my_tag.save() else: my_tag = Tag.objects.get(tag_name=current_tag) question_tag_map = QuestionTagMap(question=current_question, tag=my_tag) question_tag_map.save() return redirect(current_question) form = QuestionForm() context = { 'form': form, } return render(request, 'question/new_question.html', context)
def get(self, request): self.userAuth() form = QuestionForm(self.GET()) if not form.is_valid(): return RestResponse.frontFail("参数错误!", form.errorsDict()) data = form.cleaned_data data['questionNum'] = 10 if not data['questionNum'] else data[ 'questionNum'] dataList = Question.objects.filter(type=data['type']).values( "questionId").order_by('?')[:data['questionNum']] questionIdList = list(map(lambda x: x['questionId'], dataList)) questionList = Data.getDataList(Question, questionIdList) if data['type'] in [2, 3]: # 单选题和多选题 optionIdList = Option.objects.filter( questionId__in=questionIdList).values('optionId') optionIdList = list(map(lambda x: x['optionId'], optionIdList)) optionList = Data.getDataList(Option, optionIdList) questionOptionDict = {} for option in optionList: if option['questionId'] not in questionOptionDict: questionOptionDict[option['questionId']] = [] questionOptionDict[option['questionId']].append(option) for question in questionList: question['optionList'] = questionOptionDict[ question['questionId']] return RestResponse.success("获取题目成功!", {"questionList": questionList})
def question_edit(request, pk): item = get_object_or_404(Question, pk=pk) form = QuestionForm(request.POST or None, instance=item) if form.is_valid(): post = form.save(commit=False) post.save() # 저장하기 return redirect('/question/' + str(item.id)) return render(request, 'question/question_form.html', {'form':form})
def update(request, id): question = Question.objects.get(id=id) form = QuestionForm(request.POST, instance=question) # print(id) if form.is_valid(): form.save() # print("Hello") return redirect("/show/") return render(request, 'question/edit.html', {'question': question})
def question_create(request): if request.method == 'POST': form = QuestionForm(request.POST) if form.is_valid(): question = Question(subject=form.cleaned_data['subject'], publication_date=timezone.now()) question.save() return redirect('/questions') else: form = QuestionForm() return render_to_response('question_create.html', {'form': form}, context_instance=RequestContext(request))
def validate_question_param( cls, text_key: AnyStr, question_param: Dict, errors: Dict, question_instances: List['Question'] = None) -> (List, Dict): questions = [] for i, question_param in enumerate(question_param): question_instance = None answer_instances = [] # question_type -> type question_param['type'] = question_param.pop('question_type') if question_instances: question_instance = question_instances[i] answer_instances = question_instance.answers.all() question_form = QuestionForm(instance=question_instance, data=question_param) if not question_form.is_valid(): errors = TextAPIView.form_validation_errors( errors=errors, parent_key='{0}_question_{1}'.format(text_key, i), form=question_form) question = {'form': question_form, 'answer_forms': []} for j, answer_param in enumerate(question_param['answers']): answer_instance = None if answer_instances: answer_instance = answer_instances[j] answer_form = AnswerForm(instance=answer_instance, data=answer_param) if not answer_form.is_valid(): errors = TextAPIView.form_validation_errors( errors=errors, parent_key='{0}_question_{1}_answer_{2}'.format( text_key, i, j), form=answer_form) question['answer_forms'].append(answer_form) questions.append(question) return questions, errors
def update(request, id): question = Question.objects.get(id=id) form = QuestionForm(request.POST, instance=question) # print(id) if form.is_valid(): data = form.save() # print("Hello") messages.success(request, data.title + 'Updated Successfully') return redirect("/show/") else: # messages.error(request, "Update Failure") return render(request, 'question/edit.html', { 'question': question, 'form': form })
def edit(request, id): try: form = QuestionForm() question = Question.objects.get(id=id) return render(request, 'question/edit.html', { 'question': question, 'form': form }) except: return HttpResponse('Object not in database')
def update(request,id): question = Question.objects.get(id=id) if request.method == "POST": form = QuestionForm(request.POST, instance=question) if form.is_valid(): form.save() return redirect(resolve_url('question:detail',id)) else: form = QuestionForm(instance=question) return render(request,'question/update.html',{'form':form,'question':question})
def create(request): if request.method == "POST": # 데이터를 저장 form = QuestionForm(request.POST) if form.is_valid(): form.save() return redirect(resolve_url('question:list')) else: # 사용자에게 폼을 전달 form = QuestionForm() return render(request, 'question/create.html', {'form': form})
def create(request): if request.method == "POST": form = QuestionForm(request.POST) if form.is_valid(): try: form.save() return redirect('/show/') except: pass else: form = QuestionForm() return render(request, 'question/index.html', {'form': form})
def _get_form (self, obj): """Get question form for this representative. @param obj: this representative @type obj: representative.Representative @return: question form @rtype: forms.QuestionForm """ if 'form_question' in self.request.session: self.request.session['form_question']['representative'] =\ obj.pk else: self.request.session['form_question'] = { 'representative': obj.pk } return QuestionForm(session=self.request.session)
def create(request): if request.method == "POST": form = QuestionForm(request.POST) if form.is_valid(): question = form.save(commit=False) question.user = request.user question.save() return redirect(resolve_url("question:list")) else: form = QuestionForm() return render(request,'question/create.html',{'form':form})
def question_new(request): if request.method == 'POST': form = QuestionForm(request.POST) if form.is_valid(): question = form.save(commit=False) question.author = request.user question.save() return redirect('question:question_detail', pk=question.pk) else: form = QuestionForm() return render(request, 'question/question_form.html', {'form':form})
def create(request): if request.method == "POST": form = QuestionForm(request.POST) if form.is_valid(): data = form.save() messages.success(request, data.title + 'Added Successfully') return redirect("/show/") # else: # messages.error(request, "Unsuccessful") else: form = QuestionForm() return render(request, 'question/index.html', {'form': form})
def question_new(request): if request.POST: form = QuestionForm(request.POST) if form.is_valid(): question = form.save(request.user) return redirect('question_detail', pk=question.id) else: form = QuestionForm() is_hot = False return render( request, 'question/ask.html', {'form': form, 'profile': current_profile(request.user), 'status' : is_hot}, )
def add_question_html(request): if not request.user.is_authenticated: return redirect('/') if request.POST: aut, _ = Author.objects.get_or_create(name=request.user.username) form = QuestionForm(aut, data=request.POST) if form.is_valid(): question = form.save() return redirect( reverse("one_question_url", kwargs={'m_id': question.pk})) else: print(form.errors) return render(request, 'question/add_question.html', { 'form': form, }) else: form = QuestionForm(author=Author.objects.get(pk=1)) return render(request, 'question/add_question.html', { 'form': form, })
def question_create(request): form = QuestionForm() return render_to_response('question_create.html', {'form': form}, context_instance=RequestContext(request))
def question(request): query = None results = [] num_visits = request.session.get('num_visits', 0) request.session['num_visits'] = num_visits + 1 page = request.GET.get('page') user = None tag = None if 'query' in request.GET and 'user' is None and 'tag' is None: print('only query there') form = QuestionForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] previous_searches = Question.objects.filter( search_term__icontains=query).values_list('search_term', flat=True) if query in previous_searches: print('true it is there') results = Question.objects.filter(Q(title__icontains=query)) else: r = requests.get( 'https://api.stackexchange.com/2.2/search/advanced?order=desc&sort=activity&q=' + query + '&site=stackoverflow') answers = r.json() for i in range(len(answers['items'])): is_answered = answers['items'][i]['is_answered'] view_count = answers['items'][i]['view_count'] # closed_date=date.fromtimestamp(answers['items'][i]['closed_date']) answer_count = answers['items'][i]['answer_count'] score = answers['items'][i]['score'] last_activity_date = date.fromtimestamp( answers['items'][i]['last_activity_date']) creation_date = date.fromtimestamp( answers['items'][i]['creation_date']) question_id = answers['items'][i]['question_id'] link = answers['items'][i]['link'] # closed_reason=answers['items'][i]['closed_reason'] display_name = answers['items'][i]['owner']['user_id'] title = answers['items'][i]['title'] search_term = query question = Question.objects.create( is_answered=is_answered, view_count=view_count, link=link, answer_count=answer_count, score=score, last_activity_date=last_activity_date, creation_date=creation_date, question_id=question_id, title=title, display_name=display_name, search_term=search_term) results.append(answers['items'][i]) paginator = Paginator(results, 5) # page = request.GET.get('page') try: results = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page results = paginator.page(1) except EmptyPage: # If page is out of range deliver last page of results results = paginator.page(paginator.num_pages) return render( request, 'questionapp/questions.html', { 'form': form, 'results': results, 'query': query, 'page': page, 'num_visits': num_visits }) elif 'query' in request.GET and 'user' in request.GET and 'tag' in request.GET: print('user query') form = QuestionForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] user = form.cleaned_data['user'] tag = form.cleaned_data['tag'] previous_searches = Question.objects.filter( search_term__icontains=query).values_list('search_term', flat=True) if query in previous_searches: print('true it is there') results = Question.objects.filter( Q(title__icontains=query) | Q(display_name__icontains=query) | Q(search_term__icontains=query) | Q(search_term__icontains=user)).distinct() else: r = requests.get( 'https://api.stackexchange.com/2.2/search/advanced?order=desc&sort=activity&q=' + query + '&site=stackoverflow' + '&user='******'&tagged=' + tag) answers = r.json() for i in range(len(answers['items'])): is_answered = answers['items'][i]['is_answered'] view_count = answers['items'][i]['view_count'] # closed_date=date.fromtimestamp(answers['items'][i]['closed_date']) answer_count = answers['items'][i]['answer_count'] score = answers['items'][i]['score'] last_activity_date = date.fromtimestamp( answers['items'][i]['last_activity_date']) creation_date = date.fromtimestamp( answers['items'][i]['creation_date']) question_id = answers['items'][i]['question_id'] link = answers['items'][i]['link'] # closed_reason=answers['items'][i]['closed_reason'] display_name = answers['items'][i]['owner']['user_id'] title = answers['items'][i]['title'] for answer in answers['items']: for tag in answer['tags']: for tag_length in range(len(answer['tags'])): # print(answers['items']['tags']) print('tag wale babu zara gaana chala do') tags_present_already = Tag.objects.filter( word=tag) if not tags_present_already: tag_created = Tag.objects.create(word=tag) print(tag_created) search_term = query question = Question.objects.create( is_answered=is_answered, view_count=view_count, link=link, answer_count=answer_count, score=score, last_activity_date=last_activity_date, creation_date=creation_date, question_id=question_id, title=title, display_name=display_name, search_term=search_term) question.tags.add(tag_created) results.append(answers['items'][i]) paginator = Paginator(results, 5) # page = request.GET.get('page') try: results = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page results = paginator.page(1) except EmptyPage: # If page is out of range deliver last page of results results = paginator.page(paginator.num_pages) return render( request, 'questionapp/questions.html', { 'tag': tag, 'user': user, 'form': form, 'results': results, 'query': query, 'page': page, 'num_visits': num_visits }) elif 'query' is None and 'user' in request.GET and 'tag' is None: print('user none query there') form = QuestionForm(request.GET) if form.is_valid(): query = form.cleaned_data['user'] previous_searches = Question.objects.filter( search_term__icontains=query).values_list('search_term', flat=True) if query in previous_searches: print('true it is there') results = Question.objects.filter( Q(title__icontains=query) | Q(display_name=query)).distinct() else: r = requests.get( 'https://api.stackexchange.com/2.2/search/advanced?order=desc&sort=activity&user='******'&site=stackoverflow') answers = r.json() for i in range(len(answers['items'])): is_answered = answers['items'][i]['is_answered'] view_count = answers['items'][i]['view_count'] # closed_date=date.fromtimestamp(answers['items'][i]['closed_date']) answer_count = answers['items'][i]['answer_count'] score = answers['items'][i]['score'] last_activity_date = date.fromtimestamp( answers['items'][i]['last_activity_date']) creation_date = date.fromtimestamp( answers['items'][i]['creation_date']) question_id = answers['items'][i]['question_id'] link = answers['items'][i]['link'] # closed_reason=answers['items'][i]['closed_reason'] display_name = answers['items'][i]['owner']['user_id'] title = answers['items'][i]['title'] search_term = query question = Question.objects.create( is_answered=is_answered, view_count=view_count, link=link, answer_count=answer_count, score=score, last_activity_date=last_activity_date, creation_date=creation_date, question_id=question_id, title=title, display_name=display_name, search_term=search_term) results.append(answers['items'][i]) paginator = Paginator(results, 5) # page = request.GET.get('page') try: results = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page results = paginator.page(1) except EmptyPage: # If page is out of range deliver last page of results results = paginator.page(paginator.num_pages) return render( request, 'questionapp/questions.html', { 'form': form, 'results': results, 'query': query, 'page': page, 'num_visits': num_visits }) else: form = QuestionForm() return render(request, 'questionapp/questions.html', { 'form': form, 'num_visits': num_visits, 'results': results, })